gpt4 book ai didi

c# - C# 方法签名中的类型转换

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:50 25 4
gpt4 key购买 nike

我有 2 个类(class) AB . B继承自 A .如果我有类似的方法 void works(A aType)我可以通过 B通过键入对象就好了。但是,像 void fails(List<A> aListType) 这样的方法List<B> 失败键入 Visual Studio 提示它无法在 List<A> 之间转换和 List<B> .我可以用泛型解决这个问题,但为什么它一开始就失败了?另外,我应该只使用泛型吗?

这是一个基本的例子:

using System.Collections.Generic;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
B bType1 = new B();
works(bType1); // This works

List<B> bListType1 = new List<B>();
works(bListType1); // This works

List<B> bListType2 = new List<B>();
fails(bListType2); // This fails
}

static void works(A aType)
{
return;
}

static void works<T>(List<T> aListType) where T : A
{
return;
}

static void fails(List<A> aListType)
{
return;
}

}

class A
{

}

class B : A
{

}
}

最佳答案

那是因为 List<T>是 C# 中的 Invariant 类型,这意味着您只能使用最初在变量定义中指定的类型(即 A )。您会注意到,如果您替换 List<A>IEnumerable<A> ,你的错误消失了。这是因为 IEnumerable<A>Covariant,这意味着您可以使用比最初指定的派生类型更多的类型(即 B )。阅读更多关于 Covariance and Contravariance in C# here 的信息.

关于c# - C# 方法签名中的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32636347/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com