我不明白为什么这不起作用:
类(class):
public abstract class BaseObj
{
public bool IsValid => GetValidationErrors().Count == 0;
}
public class BaseObjWithId: BaseObj
{
public int Id { get; set; }
}
public class BaseReference<T> : BaseObj where T : BaseObjWithId
{
public T ObjReference { get; set; }
}
public class Foo: BaseObjWithId
{
public string Name{get;set;}
}
public class FooRef : BaseReference<Foo>
{
}
代码语句:
BaseReference<BaseObjWithId> foo= new FooRef();
Error CS0029 Cannot implicitly convert type...
这有效:
BaseReference<Foo> foo= new FooRef();
但我不明白为什么,因为 Foo 是一个 BaseObjWithId...
谢谢你的解释
最佳答案
您误解了泛型与类型继承的关系。您可以转换 FooRef
类型的对象进入 BaseReference<Foo>
类型的引用因为FooRef
继承自BaseReference<Foo>
。但是,您不能转换 BaseReference<Foo>
进入BaseReference<BaseObjWithID>
因为与它们用作泛型类型参数的类型不同,这两个泛型类没有这样的联系。
看下面的例子:
public class Fruit {}
public class Apple : Fruit {}
任何 Apple
对象可以存储在Fruit
中引用,因为继承可确保检查它们之间的关系:
Fruit f = new Apple();
但是,在涉及泛型的情况下,每次使用不同类型参数创建类的泛型版本时,这些版本都将被视为完全不同的类型。例如,虽然上面的隐式转换可以工作,但以下操作将会失败:
List<Fruit> f = new List<Apple>();
List<Fruit>
和List<Apple>
是完全不同的类。它们之间没有直接的转换,无论是隐式的还是显式的。
关于c# - 理解C#的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43205622/