简体   繁体   English

什么是C#中的界面强制转换?

[英]What is interface casting for in C#?

I do understand how writing an interface works in C#, as for example described here: codeguru explanation 我确实理解如何编写一个接口在C#中工作,例如这里描述的: codeguru解释

interface IIntelligence
   {
      bool intelligent_behavior();
   }

   class Human: IIntelligence
   {
      public Human()
      {
          //.............
      }

/// Interface method definition in the class that implements it
      public bool intelligent_behavior()
      {
         Console.WriteLine("........");
         return true
      }
   }

I am however confused about the following process of interface casting: 但是我对以下接口转换过程感到困惑:

Human human = new Human();
// The human object is casted to the interface type
IIntelligence humanIQ = (IIntelligence)human;
humanIQ.intelligent_behavior();

What is the sense of having a class ( Human in this case) implement an interface, and then casting its instance human back to the interface? 有一个类(在这种情况下是Human )实现一个接口,然后将它的实例人体反馈到接口的意义是什么? The question is not how it works, but why it is done. 问题不在于它是如何运作的,而是为什么要这样做。

.net offers two types of interface implementations implicit implementation and explicit implementation. .net提供了两种类型的接口实现隐式实现和显式实现。

When you are using implicit implementation , it will become part of the type interface itself for example if you have a IPerson interface like this : 当您使用隐式实现时,它将成为类型接口本身的一部分,例如,如果您有这样的IPerson接口:

public interface IPerson
{
string Name{get;}
}

and you implement it as follows : 并按如下方式实现:

public class Person:IPerson
{
public string Name{get; ....}
}

you can access it like this (implicitly): 您可以像这样(隐式)访问它:

aPerson.Name;

but if you implement it like this (explicitly) : 但如果你这样(明确地)实现它:

public class Person:IPerson
{
string IPerson.Name{get; ....} // notice that there's no need to include access modifier.
}

Then it can only be accessed using IPerson interface: 然后它只能使用IPerson接口访问:

((IPerson)aPerson).Name;

UPDATE: 更新:

Actually ,explicit interface implementation allow us to implement different interfaces with members that have same name.(as shown in this Tutorial ) 实际上,显式接口实现允许我们使用具有相同名称的成员实现不同的接口。(如本教程所示)

有时您可能不知道对象是什么,但您知道它实现了某个接口。

I found out casting to interface useful when developing plugins for main application. 我发现在为主应用程序开发插件时,转换为接口非常有用。 I created three projects. 我创建了三个项目。 First project 'connectorInterface' contains only one class definition which is inteface. 第一个项目'connectorInterface'只包含一个接口的类定义。 Interface code: 接口代码:

public interface IConnectorDataReader
{
  int ColumnCount
  {
    get;
  }

  bool readNextRecord();

  string this[int i]
  {
    get;
  }

  void reset();
}

Second project 'dataSource1' (plugin for main application) implements IConnectorDataReader interface and also class that implements interface has some additional private methods. 第二个项目'dataSource1'(主应用程序的插件)实现了IConnectorDataReader接口,实现接口的类也有一些额外的私有方法。 Third project 'main application' when using plugin 'dataSource1' uses this code to read data from plugin 'dataSource1': 使用插件'dataSource1'时,第三个项目'main application'使用此代码从插件'dataSource1'读取数据:

  Assembly assembly = Assembly.LoadFile(path); // path to dll
  Type type = assembly.GetType("dataSource1.DataReader");
  object myInstance = Activator.CreateInstance(type);

  MethodInfo method = type.GetMethod("getConnectorDataReader");
  object data = method.Invoke(myInstance, null);

  IConnectorDataReader reader =(IConnectorDataReader)data;

  // method usage
  while (reader.readNextRecord() == true) ....

In my case casting is useful to read plugins data. 在我的情况下,转换对于读取插件数据很有用。 I do not care how plugin is implemented as long as it implements common interface. 只要它实现了通用接口,我不关心插件是如何实现的。 All I care and use is common methods for reading data. 我关心和使用的只是读取数据的常用方法。 I suppose interfaces are useful and also casting back to interfaces. 我认为接口很有用,并且还可以返回接口。

It's to get access to explicit interface implementation. 这是访问显式接口实现。

Sometimes you want to hide the fact that a class implements an interface. 有时您想要隐藏类实现接口的事实。 This is done by implementing the interface explicitly. 这是通过显式实现接口来完成的。

public class MyClass : IInterface
{
     string IInterface.TheMethod(){}
}

出于同样的原因,您将派生类强制转换回它的基类。

A brief and popular example. 一个简短而流行的例子。 We can implement such code: interface IIntelligence { string Talk(); 我们可以实现这样的代码:interface IIntelligence {string Talk(); } }

   class Cat: ICreature
   {
      public string Talk()
      {
         Console.WriteLine("Meow!");
         return true
      }
   }

   class Dog: ICreature
   {
      public string Talk()
      {
         Console.WriteLine("Arf!");
         return true
      }
   }

   class Human: ICreature
   {
      public string Talk()
      {
         Console.WriteLine("Hello!");
         return true
      }
   }

And then we can use following code: 然后我们可以使用以下代码:

ICreature() creatures = new ICreature(){new Human(), new Dog(), new Cat()};
foreach(IIntelligence creature in creatures){
  Console.WriteLine(creature.Talk());
}

For more detailed information, see "Polymorphism in object-oriented programming" in google. 有关更多详细信息,请参阅Google中的“面向对象编程中的多态性”。

Consider this situation. 考虑这种情况。 I've added a method to your example. 我已经为你的例子添加了一个方法。

interface IIntelligence
{
    bool intelligent_behavior();
}

class Human: IIntelligence
{
    public Human() { }  

    /// Interface method definition in the class that implements it
    public bool IIntelligence.intelligent_behavior()
    {
        Console.WriteLine("........");
        return true;
    }    

    //Some other method definition
    public bool intelligent_behaviour()
    {
        return false;
    }
}

You would cast to IIntelligence to get the method implementation you wanted. 您将转向IIntelligence以获得您想要的方法实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM