无法转换源类型到目标类型编译错误 [英] Cannot convert source type to target type compilation error
问题描述
我有这个简单的类
public class Program
{
private static void Main(string[] args)
{
ClassB<ClassA> objA = new ClassB<ClassA>();
ClassB<ITestA<MyDTO>> objB = new ClassB<ClassA>();
}
}
public class ClassB<T>
{
///some code here
}
public interface ITestA<T>
{
///some code here
}
public class MyDTO
{
///some code here
}
public class ClassA : ITestA<MyDTO>
{
///some code
}
这行代码
ClassB<ITestA<MyDTO>> objB = new ClassB<ClassA>();
是给编译错误
is giving compilation error
Cannot implicitly convert type 'ClassB<ClassA>' to 'ClassB<ITestA<MyDTO>>
由于ClassA的实现ITestA,我不知道为什么会这样给出一个编译错误。请帮我明白我做错了。
Since ClassA implements ITestA, I don't know why would this give a compilation error. Please help me understand what am I doing wrong.
谢谢,
也先
推荐答案
这是由于所谓的仿制药的一个相当复杂的功能的方差
It's due to a rather complex feature of generics called variance.
类是不变的,这意味着如果你声明 ClassB的< T>
,创建实例然后当:
Classes are invariant, which means that if you declare ClassB<T>
, then when creating an instance:
ClassB<T1> obj = new ClassB<T2>
然后 T1
具有完全相同类 T2
。
您可以使用接口来解决这个问题,比如你的代码更改为以下,这会编译:
You can use interfaces to get around this, eg change your code to the following and it'll compile:
...
public class Program
{
private static void Main(string[] args)
{
ClassB<ClassA> objA = new ClassB<ClassA>();
IClassB<ITestA<MyDTO>> objB = new ClassB<ClassA>();
}
}
public interface IClassB<out T> // <- note the out before T
{
//some code here
}
public class ClassB<T> : IClassB<T>
{
//some code here
}
...
在这种情况下, IClassB
被声明为协变的,这意味着它可以处理被赋予一个派生类 T的
,而不需要 T
本身。周围有使用协方差(和逆变)虽然,这就是为什么一般类是默认不变风险。
In this case, IClassB
is declared as covariant, which means that it can handle being given a derived class of T
, rather than needing T
itself. There are risks around using covariance (and contravariance) though, which is why generic classes are invariant by default.
这篇关于无法转换源类型到目标类型编译错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!