![](/img/trans.png)
[英]When using dependency injection in C#, why does calling an interface method automatically call the implemented class' method?
[英]How to call a method defined in interface and implemented in class in C#?
我有一个名为IAp.cs
的接口文件,它实现了以下接口:
public interface IAp
{
Output Process(double min, double max, IEnumerable<string> items);
}
然后,我有一个这样定义的类:
[Export(typeof(IAp))]
public class Ap : IAp
{
readonly ISorter _sorter;
public Ap()
{
_sorter = ContainerProvider.Container.GetExportedValue<ISorter>();
}
Output IAp.Process(double min, double max, IEnumerable<string> items)
{
// rest removed for brevity
}
}
ISorter
接口和ContainerProvider
类的定义如下,但在单独的文件中:
interface ISorter
{
string Sort(string token);
}
internal static class ContainerProvider
{
private static CompositionContainer container;
public static CompositionContainer Container
{
get
{
if (container == null)
{
List<AssemblyCatalog> catalogList = new List<AssemblyCatalog>();
catalogList.Add(new AssemblyCatalog(typeof(ISorter).Assembly));
container = new CompositionContainer(new AggregateCatalog(catalogList));
}
return container;
}
}
}
现在,在另一个源文件中,我想调用Process
方法。 我做了这样的事情:
private readonly IAp _ap;
Output res = _ap.Process(50, 100, items);
但这表示_ap
从未分配给它,并且它为null,因此它不调用Process
方法。 它将引发NullReference
错误。
我还尝试如下初始化该类:
private Ap app = new Ap();
但是,如果我做app.
要访问其成员,它找不到Process
方法,它不存在。 有什么想法如何在另一个源文件和类中调用Process
方法吗?
您需要实例化该类,然后将其引用作为接口类型保存(因为Ap
从接口IAp
继承,因此由于多态性而合法),例如:
private readonly IAp _ap = new Ap();
Output res = _ap.Process(50, 100, items);
private IAp app = new Ap();
这是因为Ap
实现了IAp
。 之所以不能做您想做的事情,是因为您使用的是显式接口实现,所以接口方法仅在对接口的引用上可见,而在类上不可见。
另一个解决方法是不使用显式接口实现,但是这可能会使您直接引用类型,通常认为这不是最佳实践。
代码仅显示更改的签名实现。
public class Ap : IAp
{
public Output Process(double min, double max, IEnumerable<string> items)
{
// rest removed for brevity
}
}
现在,使用您现有的参考也可以。
有关更多信息,请参阅《 接口-C#编程指南》
您看到的行为是因为接口已显式实现。 您需要执行以下一项操作:
将App
实例分配给IAp
类型的变量:
IAp _ap = new Ap(); //now you can do _app.Process
隐式实现接口:
public class Ap: IAp { public Output Process(....) { ... } } Ap _ap = new Ap(); //now you can do _ap.Process
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.