如何一般在C#中实例化一个泛型类? [英] How to generically instantiate a generic class in C#?
问题描述
也许它非常简单,但我没有使用类型类型
并且它是用途。
< > =
Double
或 T
= UInt32
,取决于某个函数的结果,比如 public static Type CheckType(String input);
在代码中:
类型t = Program.CheckType(someInput);如果(t == typeof(Double))
列表< Double>或者typeof(UInt32)
,则返回typeof l =新列表< Double>();
else
列表< UInt32> l =新列表< UInt32>();
我知道上面的代码不会编译,因为我正在让 l
具有两种不同的含义(一个double列表和一个unsigned int列表)所以它会导致我的问题: p>
- 在上面的代码中是否有避免
if
的方法?
类似于此:
类型t = Program.CheckType(someInput);
列表< t> l =新列表< t>(); //我知道这不会编译...
我的意思是,一般会实例化一个通用名单...
预先感谢您!
编辑:
不是重复的 标记问题,原因只有一个: Double
和 UInt32
不是匿名类型!这里的问题是如何确定某些输入数据的类型(它将是 Type T =
typeof例如,Double)
或类型T
= typeof(UInt32)
),因此,基于该输入数据类型创建通用 SampleClass< T>
, T
!
换句话说:在运行时确定一些
类型T
,然后,使用确定的类型 T
实例化一个泛型类型。 PS:我用 List< T>
作为对话框,如下所示: SampleClass< T>
。因为你不知道类型参数,所以你可以在运行时创建一个List实例。
类型t = Program.CheckType(someInput);
类型listType = typeof(List>)MakeGenericType(t);
IList list =(IList)Activator.CreateInstance(listType);
如果您尝试添加不正确类型的对象,您将得到一个异常,所以这种方法比使用像 ArrayList
或 List
Maybe it is pretty simple, but I'm not in use with the type Type
and it's uses.
Say I want to create a List<T>
either with T
=Double
or T
=UInt32
, depending on the result of some function, say public static Type CheckType(String input);
In code:
Type t = Program.CheckType(someInput); // it returns typeof(Double) or typeof(UInt32)
if (t == typeof(Double))
List<Double> l = new List<Double>();
else
List<UInt32> l = new List<UInt32>();
I know the above code won't compile because I'm letting l
to have two different meanings (a list of double and a list of unsigned int)... So it leads to my question:
- Is there a way to avoid the
if
in the above code?
Something similar to this:
Type t = Program.CheckType(someInput);
List<t> l = new List<t>(); // I know this won't compile either...
I mean, that would generically instantiate a generic List...
Thank you in advance!
EDIT:
This is NOT a duplicate of the marked question for only one reason: Double
and UInt32
are not Anonymous types! The question, here, is how to determine the type of some input data (which will be Type T
=typeof(Double)
or Type T
=typeof(UInt32)
, for example) and, thus, create a generic SampleClass<T>
based on that input data type, T
!
In other words: determine some Type T
in the runtime and, then, instantiate a generic type with the determined type T
. Sorry if I didn't make that clear before...
PS: I used List<T>
as an example for SampleClass<T>
.
You can't type the list as generic, since you don't know the type parameter, but you can create a List instance at runtime.
Type t = Program.CheckType(someInput);
Type listType = typeof(List<>).MakeGenericType(t);
IList list = (IList) Activator.CreateInstance(listType);
If you try to add an object of the incorrect type, you will get an exception, so this approach has an advantage over using a collection like ArrayList
, or List<object>
这篇关于如何一般在C#中实例化一个泛型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!