假设我有一个List<IMyInterface>
...
我有三个实现IMyInterface
: MyClass1
,MyClass2
和MyClass3
我有一个只读字典:
private static readonly Dictionary<Type, Type> DeclarationTypes = new Dictionary<Type, Type>
{
{ typeof(MyClass1), typeof(FunnyClass1) },
{ typeof(MyClass2), typeof(FunnyClass2) },
{ typeof(MyClass3), typeof(FunnyClass3) },
};
我有另一个界面,IFunnyInteface<T> where T : IMyInterface
我有一个方法:
public static IFunnyInterface<T> ConvertToFunnyClass<T>(this T node) where T : IMyInterface
{
if (DeclarationTypes.ContainsKey(node.GetType())) {
IFunnyInterface<T> otherClassInstance = (FunnyInterface<T>) Activator.CreateInstance(DeclarationTypes[node.GetType()], node);
return otherClassInstance;
}
return null;
}
我正在尝试调用 FunnyClasses 的构造函数并将 MyClass 对象作为参数插入。我不想知道它是哪个对象:我只想用 MyClass 作为参数来实例化一些 FunnyClass。
当我调用 ConvertToFunnyClass 时会发生什么,T
是 type IMyInterface
,当我尝试将它转换为 时FunnyInterface<T>
,它说我无法转换FunnyClass1
,例如FunnyInterface<IMyInterface>
我目前的解决方法(不是一个漂亮的解决方法)是这样的:
public static dynamic ConvertToFunnyClass<T>(this T node) where T : IMyInterface
{
if (DeclarationTypes.ContainsKey(node.GetType())) {
var otherClassInstance = (FunnyInterface<T>) Activator.CreateInstance(DeclarationTypes[node.GetType()], node);
return otherClassInstance;
}
return null;
}
而且我不喜欢它,因为返回类型是dynamic
,所以当我从其他地方访问它时,我不知道它是什么类型,并且我失去了智能感知等等。我也不知道任何性能影响。
有什么线索吗?
提前致谢!
解析度
当我使用 C# 4.0 时,我可以使用协方差(仅输出位置)停止转换错误,所以我将我的更改IFunnyInterface
为
IFunnyInteface<out T> where T : IMyInterface
谢谢大家的回复。