为什么我们使用接口引用来调用对象的方法? [英] Why do we use interface references to call methods of an object?

查看:157
本文介绍了为什么我们使用接口引用来调用对象的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么我们使用接口引用来调用对象的方法?



例如:



Why do we use interface references to call methods of an object?

For example:

interface abc
{
  void xyz();
}
interface def
{
  void pqr();
}







class Program : Iabc, Idef
{
    static void Main(string[] args)
    {
        Console.WriteLine("Hello interfaces");
        Program refProgram = new Program();
        Iabc refiabc = refProgram;
        refiabc.xyz();
        Idef refidef = refProgram;
        refidef.pqr();
        Console.ReadLine();
    }
    public void pqr()
    {
        Console.WriteLine("In pqr");
    }
    public void xyz()
    {
        Console.WriteLine("In xyz");
    }
}





接口引用refiabc指向指向Program对象的refProgram引用。然后refiabc调用xyz()



为什么我们这样做(使用指向指向对象的中心引用的接口引用)而不是通过制作直接调用方法一个类的实例然后调用它的方法?



示例:



为什么这样做:





The interface reference refiabc is pointing to the refProgram reference which is pointing to the Program object. refiabc then calls xyz()

Why do we do this (use interface references that point to a central reference that points to an object) instead of calling methods directly by making an instance of a class then calling its methods?

Example:

Why do this:

Program refProgram = new Program();
        Iabc refiabc = refProgram;
        refiabc.xyz();





而不是这样做:





Instead of just doing this:

Program refProgram = new Program();
refProgram.xyz();

推荐答案

接口是合约,它们不会创造任何具体的东西 - 他们只是让你成为俱乐部成员 - 由你来实现合同所要求的功能,就像在现实世界中一样,你需要观察俱乐部要求的着装要求,并确保你支付你的费用。会员资格按时订阅。



例如,如果你实现IEnumerable,你加入可以在 foreach中使用的类的俱乐部 循环。如果你实现IEnumerable< T>>那么你可以使用Linq查询和方法。



使用接口类型而不是真实类型允许我们编写代码更灵活:如果你编写一个与接口类型一起工作的方法,那么你可以将它传递给实现接口的任何类,因为该方法不关心其他类是什么 - 它只需要使用接口相关部分。
Interfaces are a contract, they don't create anything concrete - they just let you become a "member of the club" - it is up to you to implement the functions that the contract requires, just as in the real world it is up to you to observer the dress code that a club requires and ensure that you pay your membership subscription on time.

For example, if you implement IEnumerable, you join the "club" of classes that can be used in a foreach loop. If you implement IEnumerable<T>>then you can use Linq queries and methods.

Using the interface type instead of the "real" type allows us to write code that is more flexible: If you write a method which works with the interface type, then you can pass it any class which implements the interface because the method doesn't care about what else teh class is r does - it only needs to work with the interface related parts.


当然我们可以直接调用这些方法,但只有通过对类实例的引用才能访问这些方法。实现接口的方法不必是公共的,它们可以是显式实现方法:

Of course we can call those methods directly, but only if these methods are accessible via the reference to the class instance. The methods implementing interfaces don't have to be public, they can be explicit implementation method:
interface MyInterface {
   void MyMethod();
}

class MyClass : MyInterface {
    // this method cannot be called using the reference to MyClass:
    void MyInterface.MyMethod(); 
}



您可能会问:为什么要做这样的事情,为什么不使用公共方法在所有情况下隐式实现接口?我会回答:因为它可以让你做你想要的,直接调用接口实现方法,通过引用实现类的实例。这就是为什么在大多数情况下,上面显示的显式实现更好。



你感到惊讶吗?我告诉你,真正的好处是不允许你做你想做的事情!那就对了。你想要什么是可能的,但这很糟糕,并非总是如此,但在大多数情况下。 这很糟糕,因为它会破坏接口的目的。



接口是一个功能强大的抽象设备这有助于您将某些合同与其实施隔离开来。您应该了解变量/成员的运行时类型可能与编译时类型不同。接口类型只能是编译时类型,但它们永远不能是任何对象的运行时类型;如果你愿意的话,它们总是抽象的,就像抽象类型一样。这是OOP的基础,后期绑定和多态性。您使用常见的合同与该合同的不同实现,从实现中抽象出来。编程的全部思想都是关于抽象的。



这里非常重要的一点是:接口提供了比基类更强的多态性。这是因为结构(值类型!)也可以实现接口,而不仅仅是一个类,并且因为接口可以使用多态,所以同一个对象可以参与两个或多个不同的多态集,抛出两个或多个不同的接口引用。有了课程,这些可能性就完全丧失了。您直接调用接口方法的想法意味着失去接口的所有好处。



请查看我过去的答案:

对接口的怀疑 [ ^ ],

没有过载和过度使用的多态性可能 [ ^ ],

接口和多态性 [ ^ ],

如何决定选择抽象类或接口 [ ^ ],

抽象类和接口之间的区别,如果它们具有相同的no方法和var [ ^ ],

当我们使用抽象时,当我们使用接口时......? [ ^ ]。



-SA


You might ask: why doing such things at all, why not implementing interfaces implicitly in all cases, using public methods? I'll answer: because it would allow you to do what you want, directly calling interface implementation methods, through the reference to the instance of implementing class. That's why, in most cases, explicit implementation shown above is better.

Are you surprised? I am telling you that the real benefit is not to allow you to do what you want! That's right. What you want is possible, but this is bad, not always, but in most cases. This is bad because it would defeat the purpose of the interfaces.

The interface is a powerful abstraction device which helps you to isolate some contract from its implementation. You should understand that the runtime type of a variable/member can be not the same as the compile-time type. Interface types can be compile-time types only, but they can never be a runtime-types of any objects; if you will, they are always abstract, the same way as abstract types. This is the base of OOP, late binding and polymorphism. You use the common contract with different implementations of that contract, abstracting from the implementation. And whole idea of programming is all about abstraction.

A very non-trivial point here is: interfaces provides "stronger polymorphism" than base classes. This is because a structure (a value type!) can also implement interface, not only a class, and because interfaces can use polymorphism, so the same object can participate in two or more different polymorphic sets, throw two or more different interface references. With classes, these possibilities are totally lost. Your idea to call interface methods directly means loosing all benefits of interfaces.

Please see my past answers:
Doubts on Interfaces[^],
POLYMORPHISM WITHOUT OVERLOADING AND OVERRRIDING IS POSSIBLE[^],
Interfaces and Polymorphism[^],
How to decide to choose Abstract class or an Interface[^],
Difference between abstract class and interface if they have same no of methods and var[^],
When we use abstract and when we use interface...?[^].

—SA


这篇关于为什么我们使用接口引用来调用对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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