在C#中通过其接口引用类 [英] Referencing a class through its interface in C#

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

问题描述

我很好奇是否有人通过他们项目中的接口引用类?我正在使用这个示例,其中接口ILandBound与类Horse一起引用,正如您在实现中从底部的两行看到的那样,对象
通过接口引用。这种方法有什么优势吗?
I am curious if anyone is referencing classes through interfaces in their projects? I am working with this example here where interface ILandBound is referenced with the class Horse and as you see from the bottom two lines in implementation the object is referenced through an interface. Is there any advantage in this approach?

推荐答案

你创建了一个存在于内存中的Horse实例。

You created an instance of Horse that lives in memory.

第二个,你拿了马的例子并且做了iMyhorse 马的例子。无论哪种方式,接口都是用Horse实现的,所以两个对象都在使用接口。

The second one, you took the instance of Horse and made iMyhorse  the instance of Horse. Either way, the Interface is implemented in Horse, so both objects are using the Interface.

除此之外我没有任何优势。

There is no advantage that I know about other than this.

A 正在使用构造函数的类 这是使用类的接口实现将类的对象实例注入需要使用类中注入对象实例的类/对象,这称为依赖
注入。

A  class that is using a constructor  that is using a class's Interface implementation to inject the object instance of a class into the class/object that needs to use the instance of the injected object in the class, which is called dependency injection.

public class TheClass
{
        private Natasaha thenat.
         public TheClass(INatasaha nat)
         {
              thenat = nat;
         }
          public void SomeMethod()
         {
              thenat.HelpMe();
         }
}

var theclass = new TheClass(new  Natasaha() );

var theclass = new TheClass(new Natasaha());

theclass.SomeMethod()。

theclass.SomeMethod().

或 

new TheClass(新的Natashaha())。SomeMethod();

new TheClass(new Natashaha()).SomeMethod();

无论如何,  Natasaha类的实例将根据实现的方式传递给TheClass我 Natasaha在  Natasaha类上实现,该方法在TheClass.SomeMethod中的thenat对象中执行
( ) 当实例作为对象时,Natasaha实例可用于TheClass。

Either way above, the instance of the Natasaha class is being passed into TheClass based on the implementation of the INatasaha implemented on the Natasaha class, and the method is executed in the thenat object within the TheClass.SomeMethod() with  Natasaha instance made available to the TheClass when it is instanced as an object.

Capiche?

 


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

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