如何调用扩展接口的类? [英] How can I call a class that extends interface?
本文介绍了如何调用扩展接口的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个接口类:
I have a interface class:
public interface IStatFunction : IComparable<IStatFunction>
{
}
和普通类扩展IStatFunction接口:
and normal class extends IStatFunction interface:
public class StatFunction : IStatFunction
{
}
现在我的代码将同时使用上面的类和接口:
Now my code will use both of above class and interface:
public void addEffect(IStatOwner statOwner, List<IStatFunction> functions)
{
}
其他代码调用此addEffect函数:
other code call this addEffect function:
List<StatFunction> allModifiers = null;
cgs.addEffect(item, allModifiers);
现在我收到错误:无法转换List< statfunction>列表< istatfunction>
我该如何解决这个错误?
我是什么尝试过:
我试图使用ConvertAll,它可以删除错误,但我不知道它的工作:
Now i get error: Cannot convert List<statfunction> to List<istatfunction>
so how can i fix this error?
What I have tried:
Im trying to use ConvertAll, its can remove error but i dont know its work or not:
cgs.addEffect(item, allModifiers.ConvertAll(o => (IStatFunction)o));
推荐答案
为什么这么复杂 - 协方差和逆变(计算机科学) - 维基百科 [ ^ ]有助于解释它 - 但它很容易解决:
It's complicated as to why - Covariance and contravariance (computer science) - Wikipedia[^] helps to explain it - but it's simple to fix:
public void addEffect<T>(IStatOwner statOwner, List<T> functions) where T : IStatFunction
{
...
}
这篇关于如何调用扩展接口的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文