C# How to use interfaces

前端 未结 4 768
不知归路
不知归路 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 20:59

    First off, you need to have your Test class inherit/implement ITest.

    class Test : ITest
    {
        public string TestMethod() { return "test"; }
    }
    

    Then, in your controller class, you need to initialize test -- whether directly, or in the constructor.

    public class HomeController : Controller
    {
        public ITest test = new Test();
        public ActionResult Index()
        {
            return Content(test.TestMethod());
        }
    }
    

    Although in many cases, you should prefer to create the ITest outside of the constructor and pass it in or something.

提交回复
热议问题