<分区>
是否可以在设计时不知道类型的情况下声明泛型实例?
例子:
Int i = 1;
List<typeof(i)> list = new List<typeof(i)>();
i 的类型可以是任何东西,而不必做:
List<int> list = new List<int();
<分区>
是否可以在设计时不知道类型的情况下声明泛型实例?
例子:
Int i = 1;
List<typeof(i)> list = new List<typeof(i)>();
i 的类型可以是任何东西,而不必做:
List<int> list = new List<int();
最佳答案
如果您在编译时不知道类型,但您想要实际类型(即不是 List<object>
)并且您不在具有适当的泛型方法/类型中类型参数,那么你必须使用反射。
为了使反射更简单,我有时会在自己的代码中引入新的泛型类型或方法,这样我就可以通过反射调用它,然后再使用普通的泛型。例如:
object x = GetObjectFromSomewhere();
// I want to create a List<?> containing the existing
// object, but strongly typed to the "right" type depending
// on the type of the value of x
MethodInfo method = GetType().GetMethod("BuildListHelper");
method = method.MakeGenericMethod(new Type[] { x.GetType() });
object list = method.Invoke(this, new object[] { x });
// Later
public IList<T> BuildListHelper<T>(T item)
{
List<T> list = new List<T>();
list.Add(item);
return list;
}
当然,如果您不知道类型,您之后就不能对列表做很多事情……这就是为什么这种事情经常失败的原因。但并非总是如此 - 我在一些场合使用过类似上面的东西,其中类型系统并不能完全让我静态地表达我需要的一切。
编辑:请注意,虽然我在上面的代码中调用了 Type.GetMethod,但如果您要多次执行它,您可能只想调用它一次 - 毕竟,该方法不会改变。您可以将其设为静态(在上述情况下可以)并且您可能也想将其设为私有(private)。为了简化示例代码中的 GetMethod 调用,我将其保留为公共(public)实例方法 - 否则您需要指定适当的绑定(bind)标志。
关于c# - 动态声明泛型类型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/307984/