c# - 理解C#的类型转换

标签 c#

我不明白为什么这不起作用:

类(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/

相关文章:

c# - 将您的请求存储在带有Nest的Elasticsearch缓存中?

c# - 如何保证数据一致性

c# - checkin : Operation not performed Could not find file *. csproj.vspscc

c# - 使用 HttpWebResponse 加载页面的时间太长

c# - WCF流式文件传输

c# - 是否有一个库可以使 C#/.NET/ASP.NET 中的 html 更容易

c# - Action/Func vs Methods,有什么意义?

c# - 如何以非管理员身份检查本地安全策略权限

c# - 包含来自网络的动态库

c# - 保护 Azure 功能的方法有哪些