在我的程序中,我有一个类 A
扩展为 B
, C
以及更多类(class)。我有一个方法GetInstance()
它返回 B
的实例或C
(或其他子级之一),但我不知道是哪一个,因此该方法的返回类型是 A
.
在方法CreateGenericList()
中,我有一个变量 v
类型 A
,实际上是 B
,一个C
或其他子类型,我想创建正确类型的通用列表,即 List<B>
如果v
是 B
或List<C>
如果v
是 C
,...
目前我通过使用反射来做到这一点,它可以工作,但是速度非常慢。我想知道是否有另一种不使用反射的方法来做到这一点。
这是我的问题的代码示例:
class A { }
class B : A { }
class C : A { }
// More childs of A.
class Program
{
static A GetInstance()
{
// returns an instance of B or C
}
static void CreateGenericList()
{
A v = Program.GetInstance();
IList genericList = // Here I want an instance of List<B> or List<C> or ... depending of the real type of v, not a List<A>.
}
}
我尝试了以下技巧。我调用以下方法,希望类型推断器能够猜测 model
的类型,但它不起作用并返回 List<A>
。我相信因为 c# 是静态类型的, T
解析为 A
而不是 model
的真实类型在运行时。
static List<T> CreateGenericListFromModel<T>(T model) where T : A
{
return new List<T> ();
}
是否有人可以解决不使用反射的问题,或者不使用反射就不可能解决该问题?
非常感谢。
最佳答案
如果不进行反射,就无法解决这个问题,因为必须在编译时知道泛型类型参数。如果您知道自己的类型(例如 if(v[0] is B)
),则可以使用 v.Cast<B>()
将其从 List<A>
转换至IEnumerable<B>
,您可以通过调用 ToList()
再次将其转换为列表。 .
关于c# - 如何在 C# 中的这种奇怪情况下创建通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2965280/