gpt4 book ai didi

c# - 无法将 List 转换为 List

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

我有一个像这样的通用函数:

public List<T> DoStuff<T>(){
if(typeof(T) == typeOf(ClassA))
return CreateListWithTypeA();
if(typeof(T) == typeOf(ClassB))
return CreateListWithTypeB();
}

还有这里的助手:

public List<ClassA> CreateListWithTypeA(){
return new List<ClassA>();
}
public List<ClassA> CreateListWithTypeB(){
return new List<ClassA>();
}

DoStuff() 错误:

Cannot convert type System.Collection.Generic.List<ClassA> to System.Collection.Generic.List<T>

PS: ClassA & ClassB 实现了一个接口(interface)。不确定这是否有帮助

最佳答案

我不认为这是对泛型的很好的使用,因为它将 T 限制为两种类型中的一种。

但如果您坚持,下面是修复方法的方法:

public static List<T> GetList<T>() where T : YourInterface { // The constraint here provides just a *bit* more compile time checking
if (typeof(T) == typeof(A)) {
return CreateListWithTypeA().Cast<T>().ToList();
}

// other cases here...

throw new Exception("T is not the right type!");
}

关于c# - 无法将 List<ClassA> 转换为 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53030368/

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