假设我在一个名为“Interface”的项目中有一个这样的接口(interface):
public interface TestInterface
{
string Operation();
}
以及实现它的类。该类位于另一个项目“Class”中:
public class TestClass : TestInterface
{
public TestClass() { }
public string Operation()
{
return "This is an Operation";
}
}
我的客户做了这样的事情(这又是在另一个项目“Client”中):
class Program
{
static void Main(string[] args)
{
TestInterface i = new TestClass();
i.Operation();
}
}
我的问题与此行相关:
TestInterface i = new TestClass();
通过添加这一行,我实际上被迫添加对“客户端”项目中的“接口(interface)”和“类”项目的引用。那么为什么这么大惊小怪呢?我不能直接引用“类”而不保留“接口(interface)”吗?有没有办法仅通过接口(interface)访问方法(而不引用实现类)?我在这里遗漏了什么吗?
最佳答案
Is there any way to access the methods via Interface only
是的,有。您可以使用 TestClass
动态加载程序集而不引用它,通过 Activator.CreateInstance
创建其实例并将其转换为接口(interface)类型:
var assembly = Assembly.Load(...);
var typeFromAssembly = assembly.GetTypes()...;
var myInterfaceVar = (TestInterface)Activator.CreateInstance(typeFromAssembly);
...或者...您可以使用现有的 DI 框架之一(例如 MEF)并以更正确的方式做同样的事情:
[Import]
private TestInterface myInterfaceField;
或者:
var myInterfaceVar = compositionContainer.GetExportedValue<TestInterface>();
根据您喜欢的方式,您可以提出更具体的问题。
关于c# - 访问接口(interface)方法而不引用类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14498464/