C#中接口转换的作用是什么?

7

我理解在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
      }
   }

然而,我对接口转换的以下过程感到困惑:

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

在IT技术中,为什么要让一个类(例如Human)实现一个接口,并将其实例human强制转换回接口?这个问题不是如何实现,而是为什么这样做。

7个回答

4

.net提供两种接口实现方式:隐式实现和显式实现。

当你使用隐式实现时,它将成为类型接口本身的一部分。例如,如果你有一个像这样的IPerson接口:

public interface IPerson
{
string Name{get;}
}

你可以按照以下方式实现它:
public class Person:IPerson
{
public string Name{get; ....}
}

您可以像这样访问它(隐式):
aPerson.Name;

但是如果你像这样(显式地)实现它:
public class Person:IPerson
{
string IPerson.Name{get; ....} // notice that there's no need to include access modifier.
}

那么它只能通过IPerson接口访问:

((IPerson)aPerson).Name;

更新:

事实上,显式接口实现允许我们使用相同名称的成员实现不同的接口。(如此教程所示)


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

我猜你可以用 baseObject is IInterface 进行检查。有趣的是方法参数本来就没有被定义为 IInterface 类型。 - Jodrell

1
一个简短而受欢迎的例子。我们可以实现这样的代码: 接口 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
      }
   }

然后我们可以使用以下代码:

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

如需更详细的信息,请在谷歌中查看“面向对象编程中的多态性”。


0
出于同样的原因,您会将派生类转换回其基类。

0

我发现在开发主应用程序的插件时,将类型转换为接口非常有用。我创建了三个项目。第一个项目“connectorInterface”仅包含一个类定义,即接口。接口代码:

public interface IConnectorDataReader
{
  int ColumnCount
  {
    get;
  }

  bool readNextRecord();

  string this[int i]
  {
    get;
  }

  void reset();
}

第二个项目“dataSource1”(主应用程序的插件)实现了IConnectorDataReader接口,而且实现该接口的类还有一些额外的私有方法。第三个项目“主应用程序”在使用插件“dataSource1”时,使用以下代码从插件“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) ....

在我的情况下,强制类型转换对于读取插件数据非常有用。只要插件实现了通用接口,我就不关心插件的实现方式。我关心和使用的是读取数据的通用方法。我认为接口很有用,同时也可以向接口进行强制类型转换。

0

这是为了获得访问显式接口实现的权限。

有时候你想要隐藏一个类实现了一个接口的事实。这可以通过显式实现接口来完成。

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

0
考虑这种情况。我已经在你的示例中添加了一个方法。
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;
    }
}

你需要将类型转换为 IIntelligence 才能获取你想要的方法实现。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接