Rob*_*rth 174 .net c# generics
标题有点模糊.我想知道的是,如果可能的话:
string typeName = <read type name from somwhere>;
Type myType = Type.GetType(typeName);
MyGenericClass<myType> myGenericClass = new MyGenericClass<myType>();
Run Code Online (Sandbox Code Playgroud)
显然,MyGenericClass被描述为:
public class MyGenericClass<T>
Run Code Online (Sandbox Code Playgroud)
现在,编译器抱怨'找不到类型或命名空间'myType'."必须有办法做到这一点.
Jon*_*eet 211
没有反思,你不能这样做.但是,你可以用反射来做.这是一个完整的例子:
using System;
using System.Reflection;
public class Generic<T>
{
public Generic()
{
Console.WriteLine("T={0}", typeof(T));
}
}
class Test
{
static void Main()
{
string typeName = "System.String";
Type typeArgument = Type.GetType(typeName);
Type genericClass = typeof(Generic<>);
// MakeGenericType is badly named
Type constructedClass = genericClass.MakeGenericType(typeArgument);
object created = Activator.CreateInstance(constructedClass);
}
}
Run Code Online (Sandbox Code Playgroud)
注意:如果您的泛型类接受多种类型,则在省略类型名称时必须包含逗号,例如:
Type genericClass = typeof(IReadOnlyDictionary<,>);
Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
76220 次 |
| 最近记录: |