这是一个相当基本的 C# 问题;抱歉,我在其他地方找不到这个。
从 Object<class>
转换的最佳方式是什么?至Object<interface>
?
即
//fake interface
interface ignu {}
//fake class which implements fake interface
class bee : ignu {}
//function which accepts a generic with the interface
function bang(template<bee>) {}
//template type but with a class that implements the interface
template<bar> foo;
//trying to call the function, but compiler complains it can't implicitly convert
bang(foo);
//compilers complains that it cannot convert from template<bee> to template<ignu>
bang((template<ignu>)bee)
也许我偏离了基地,但这似乎应该可行并且可行,但解决方案却让我无法理解。
编辑:将 mygen 更改为模板,因为我使用两者来指代相同的事物,这令人困惑
编辑:我最终使用了类似于: 砰(bee.Cast());
最佳答案
无法保证 Generic<SubType>
实际上可以用作 Generic<BaseType>
的替代品.
考虑一下:
List<int> intlist = new List<int>();
List<object> objlist = intlist; // compile error
objlist.Add("foo"); // what should be in intlist now?
您正在寻找的称为协方差和逆变方差。它们已添加到 c#4 中。
关于泛型参数的 C# 类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3559505/