[英]Casting generics and the generic type
考虑一下,我有以下3个类/接口:
class MyClass<T> { }
interface IMyInterface { }
class Derived : IMyInterface { }
我希望能够将MyClass<Derived>
转换为MyClass<IMyInterface>
,反之亦然:
MyClass<Derived> a = new MyClass<Derived>();
MyClass<IMyInterface> b = (MyClass<IMyInterface>)a;
但是如果我尝试,我会遇到编译错误:
Cannot convert type 'MyClass<Derived>' to 'MyClass<IMyInterface>'
我确信有一个很好的理由我不能这样做,但我想不出一个。
至于为什么我想这样做 - 我想象的场景是你理想地希望使用MyClass<Derived>
的实例以避免许多讨厌的演员,但是你需要将你的实例传递给一个接口接受MyClass<IMyInterface>
。
所以我的问题是双重的:
MyClass<Derived>
实例的MyClass<Derived>
同时仍然能够将其转换为MyClass<IMyInterface>
? 这不起作用,因为C#仅支持接口和委托的类型参数的协方差。 如果你的类型参数仅存在于输出位置(即你只从类中返回它的实例而不接受它作为参数),你可以创建一个这样的接口:
interface IClass<out T> { }
class MyClass<T> : IClass<T> { }
这将允许你这样做:
IClass<Derived> a = new MyClass<Derived>();
IClass<IMyInterface> b = a;
老实说,这与你将要获得的一样接近,这需要C#4编译器才能工作。
你一般不能这样做的原因是因为大多数类都不是简单的空例子。 他们有方法:
class MyClass<T>
{
static T _storage;
public void DoSomethingWith(T obj)
{
_storage = obj;
}
}
interface IMyInterface { }
class Derived : IMyInterface { }
MyClass<Derived> a = new MyClass<Derived>();
现在, a
有一个方法DoSomethingWith
接受一个Derived
并将其存储在类型的一个静态变量Derived
。
MyClass<IMyInterface> b = (MyClass<IMyInterface>)a;
如果允许, b
现在看起来有一个方法DoSomethingWith
接受任何实现IMyInterface
东西 ,然后在内部尝试将它存储在Derived
类型的静态变量中,因为它仍然是a
引用的同一个对象。
所以现在你有一个Derived
存储类型的变量......谁知道什么。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.