简体   繁体   English

如何使用带接口的方法

[英]How to use an interface with method

I'm not sure if the terms I'm using is right or not, but basically I want something like this. 我不确定我使用的术语是否正确,但是基本上我想要这样的东西。

public interface IMovements
{
    Boolean Run(string mammal);
}
public MovementService: IMovement
{
    public Boolean Run(string mammal)
    {
       if(mammal == human)
       {
         Console.WriteLine("Human is now running");
         return true;
       }
       else
       {
         Console.WriteLine("This creature can't run");
         return false;
       }
    }
}

Then in the main class I just wanna call just the interface to execute the run operation. 然后在主类中,我只想调用接口来执行运行操作。

[Dependency]
IMovement Mov {get; set; }

//Do something with Mov
Mov.Run("Human");

Move.Run("Worm");

And the output would be: 输出将是:

Human is now running
This creature can't run

If you want to inject dependency as an interface you have options like 如果您想将依赖项作为接口注入,则可以选择以下选项

  • constructor injection where you pass interface and Dependency injection framework like Ninject will instantiate it for you 传递接口的构造函数注入,像Ninject这样的依赖注入框架将为您实例化它
  • property injection as you describe. 您所描述的属性注入。 MEF from Microsoft can do this with [Import] Attribute. Microsoft的MEF可以使用[Import]属性来执行此操作。 And also Unity with [Dependency] Attribute. 以及带有[Dependency]属性的Unity。

This seems to be about a classical Interface misconception. 这似乎是关于经典接口的误解。 A bit of history: The Designers of .NET wanted to avoid a lot of problems that were common at the time. 一段历史:.NET的设计师希望避免当时很多常见的问题。

Multiple Inheritance leads to the Diamond problem and it is one of the things they wanted to solve. 多重继承会导致钻石问题 ,这是他们想要解决的问题之一。 So they decided: In .NET there will be Single Inheritance only. 因此,他们决定:在.NET中,将只有“单一继承”。

But with single inhertiance has it's own set of issues so they needed to invent something close to multiple Inheritance it, without creating the Diamond Problem. 但是单继承有它自己的一系列问题,因此他们需要发明接近多继承的东西,而不产生钻石问题。 Interfaces were the solution. 接口是解决方案。

Interfaces are - in lack of a better term - more abstract then a abstract class. 接口-缺乏更好的术语-比抽象类更抽象。

  • A abstrtact class may or may not include code. 摘要类可能包含也可能不包含代码。 That is up to the programmer writing it 这取决于程序员编写它
  • A interface can not ever incldue code 接口永远无法添加代码

You can only put one abstract calss into the inheritance chain. 您只能将一个抽象cals放入继承链。 But you can put as many Interfaces as you want there. 但是您可以在其中放置任意数量的接口。 As they lack function implementations, they never cause that diamond problem. 由于它们缺少功能实现,因此它们永远不会引起钻石问题。

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

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