C#如何使用接口 [英] C# How to use interfaces
问题描述
这是一个相对直截了当的问题。但我想知道通过使用接口访问单独项目中的方法的正确用法是什么。
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.
项目: Test.ClassLibrary
界面:
public interface ITest
{
string TestMethod();
}
等级:
public class Test : ITest
{
public string TestMethod()
{
return "Test";
}
}
项目: Test.Web
控制器:
public class HomeController : Controller
{
private ITest test;
public ActionResult Index()
{
return Content(test.TestMethod());
}
}
以上返回的NullReferenceException
。我假设它是因为控制器到达接口,并且不知道接下来要去哪里。
The above returns a NullReferenceException
. I'm assuming it's because the controller gets to the interface, and doesn't know where to go next.
解决此问题的最佳方法是什么?我是否必须在控制器中引用 Test
类,或者我可以通过仅引用 ITest
?
What's the best way to fix this? Do I have to reference the Test
class in the controller or can I some how get away with only having a reference to ITest
?
推荐答案
- 你永远不会实例化
ITest测试
,你只声明它。 - 你的
测试
类不会从界面继承。 - 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
{
在你的控制器中,实例化 test
。
And in your controller, instantiate test
.
ITest test = new Test();
随着您的进一步发展,您将需要探索注入在控制器中测试
实例,这样你就不会有硬依赖,而只是在接口 ITest
上。评论提及IoC或控制反转,但您应该研究各种依赖性反转技术技术(IoC是其中之一,依赖注入等)。
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).
这篇关于C#如何使用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!