C# How to use interfaces

前端 未结 4 767
不知归路
不知归路 2021-02-12 20:15

This is a relatively straight forward question. But I was wondering what the correct usage is for accessing a method inside a separate project through the use of an interface.

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-12 21:06

    • You never instantiate ITest test, you only declare it.
    • Your Test class doesn't inherit from the interface.

    You need to update your class declaration

    public class Test : ITest // interface inheritance 
    {
    

    And in your controller, instantiate test.

    ITest test = new Test();
    

    As you get further along, you'll want to explore techniques for injecting the Test instance into the controller so that you do not have a hard dependency upon it, but just on the interface ITest. A comment mentions IoC, or Inversion of Control, but you should look into various Dependency Inversion techniques techniques (IoC is one of them, dependency injection, etc).

提交回复
热议问题