什么是接口铸造在C#中? [英] What is interface casting for in C#?

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

问题描述

我不知道如何在C#编写的接口工作,例如这里描述:
codeguru解释

I do understand how writing an interface works in C#, as for example described here: codeguru explanation

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? The question is not how it works, but why it is done.

推荐答案

.NET提供了两种各类接口实现隐实施和明确的实现。

.net offers two types of interface implementations implicit implementation and explicit implementation.

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

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 :

public interface IPerson
{
string Name{get;}
}

和你实现它如下:

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.
}



那么就只能使用IPerson接口来访问:

Then it can only be accessed using IPerson interface:

((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)

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

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