了解C#中的接口 [英] Understanding interface in C#

查看:74
本文介绍了了解C#中的接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hello Folks,
今天,我正在研究C#中的接口概念,并遇到了有关接口的示例.请参阅以下内容:

接口代码:

Hello Folks,
Today I was going through concepts of Interfaces in C# and came across an example on Interface. Please see the following:

Interface code:

using System;
using System.Collections.Generic;
using System.Text;
namespace ClassLibrary1
{
    public interface IAClass
    {
        int AddNumber(int a, int b);
    }
    public interface IBClass
    {
        int AddNumber(int a, int b);
    }
    public class Class1: IAClass, IBClass
    {
        public int AddNumber(int a, int b)
        {
            return a + b;
        }
    }
}



控制台应用代码:



Console Application Code:

using System;
using System.Collections.Generic;
using System.Text;
using ClassLibrary1;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            IBClass obj = new Class1();

            Console.WriteLine(obj.AddNumber(3, 6));
        }
    }
}



我得到的输出为9,这是正确的.现在我的问题是,我在两个接口中都声明了相同的方法,并且具有相同的签名. Class1正在实现这两个接口.如果我创建的IAClass或IBClass输出的对象相同,则编译器如何理解应调用的方法?
为什么它不会引发任何错误?



I am getting the output as 9, which is correct. Now my question is that I have declared same method in both interfaces, with same signature. Class1 is implementing both Interfaces. If I am creating the object of IAClass or IBClass output is same, how does the compiler understand that which method it should call?
Why is it not throwing any error?

推荐答案

您的接口只是一个契约,它声明实现该接口的任何类都必须满足该接口中所述的条件. br/>
在您的示例中,两个接口都指定了相同的方法要求,并且当您的类满足此要求时,两个接口都同样满意.

只要满足要求,编译器就不会在意该方法的实现方式,因此没有错误.
Your interface is simply a contract it states that any class that implements it must satisfy the criteria as stated in the interface.

In your example both interfaces specify the same method requirement and as your class satisfies this requirement both interfaces are equally happy.

There is no error as the compiler does not care how the method is implemented as long as the requirement is met.


您的实现类将具有一个方法,并且这将满足两个接口的要求.不管引用什么类型的引用变量,都将始终执行相同的方法.

检查一下.

http://stackoverflow.com/questions/4638218/class-实现两个接口定义相同的方法 [
Your implementing class will have one method and this will satisfy the requirements of both interfaces. It doesn''t matter what type of reference variable it calls, the same method will always be executed.

Check this.

http://stackoverflow.com/questions/4638218/class-implementing-two-interfaces-which-define-the-same-method[^]


这篇关于了解C#中的接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆