Mar*_*ell 21
您可以添加: new()约束:
void Foo<T>() where T : class, new() {
T newT = new T();
// do something shiny with newT
}
Run Code Online (Sandbox Code Playgroud)
如果你没有约束,那么Activator.CreateInstance<T>可以帮助(减去编译时检查):
void Foo<T>() {
T newT = Activator.CreateInstance<T>();
// do something shiny with newT
}
Run Code Online (Sandbox Code Playgroud)
如果你的意思是你自己的类型,那么可能是这样的:
Type itemType = typeof(int);
IList list = (IList)Activator.CreateInstance(
typeof(List<>).MakeGenericType(itemType));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5450 次 |
| 最近记录: |