c#-可以从c#类型转换为System.type,但不能从c#类型转换为System.type
我可以创建一个泛型类,将C#type作为其模板参数,然后在泛型类中使用系统。与该C#type对应的类型信息:c#-可以从c#类型转换为System.type,但不能从c#类型转换为System.type,c#,generics,C#,Generics,我可以创建一个泛型类,将C#type作为其模板参数,然后在泛型类中使用系统。与该C#type对应的类型信息: 公共类泛型 { 公共图书馆 { 返回类型为(T).IsArray(); } 公共文件不能创建() { 返回blah(); } } Generic gi=新的Generic(); Debug.WriteLine(“int isarray=“+gi.isarray()); 通用gdt; 但现在让我们说,我拥有的是一个System.Type。我不能用它来实例化我的泛型类: FieldInfo
公共类泛型
{
公共图书馆
{
返回类型为(T).IsArray();
}
公共文件不能创建()
{
返回blah();
}
}
Generic gi=新的Generic();
Debug.WriteLine(“int isarray=“+gi.isarray());
通用gdt;
但现在让我们说,我拥有的是一个System.Type。我不能用它来实例化我的泛型类:
FieldInfo field = foo();
Generic<field.FieldType> g; // Not valid!
FieldInfo-field=foo();
通用g;//无效!
我能做些聪明的C#事情,把System.Type转换回原来的C#Type吗?或者以其他方式创建泛型,该泛型可以(1)向我提供有关System.Type的信息,以及(2)创建关联C#类型的对象
顺便说一句,这是一个非常做作的例子来解释我试图解决的问题,不要太担心泛型是否有意义 你唯一能做的就是使用反射。这是因为
Generic
的int
在编译时已知,而字段.FieldType
仅在运行时已知
反射示例:
Type type = typeof(Generic<>).MakeGenericType(field.FieldType);
// Object of type Generic<field.FieldType>
object gen = Activator.CreateInstance(type);
- 接口/基类:您有一个非泛型基类或接口,它在所有
之间是通用的。只能通过该接口/基类使用对象泛型
公共类泛型:i可比较,其中T:new()
{
公共图书馆
{
返回类型(T).IsArray;
}
公共文件不能创建()
{
返回新的T();
}
公共整数比较(对象对象对象)
{
返回0;
}
}
Type Type=typeof(Generic).MakeGenericType(field.FieldType);
IComparable cmp=(IComparable)Activator.CreateInstance(类型);
int res=cmp.CompareTo(cmp);
- 一种通用方法,在该方法中,您可以放置
的所有处理。这是通过反射使用的唯一方法通用
publicstaticvoidworkwitht(),其中T:new()
{
Generic g=新的Generic();
T obj=g.Create();
Console.WriteLine(g.IsArray());
}
var method=typeof(Program).GetMethod(“WorkWithT”).MakeGenericMethod(field.FieldType);
//单一反射使用。使用无反射的内部工作。
调用(null,null);
Type type = typeof(Generic<>).MakeGenericType(field.FieldType);
// Object of type Generic<field.FieldType>
object gen = Activator.CreateInstance(type);
Type type = typeof(Generic<>).MakeGenericType(field.FieldType);
// Object of type Generic<field.FieldType>
object gen = Activator.CreateInstance(type);
MethodInfo isArray = type.GetMethod("IsArray");
bool result = (bool)isArray.Invoke(gen, null);
public class Generic<T> : IComparable where T : new()
{
public bool IsArray()
{
return typeof(T).IsArray;
}
public T Create()
{
return new T();
}
public int CompareTo(object obj)
{
return 0;
}
}
Type type = typeof(Generic<>).MakeGenericType(field.FieldType);
IComparable cmp = (IComparable)Activator.CreateInstance(type);
int res = cmp.CompareTo(cmp);
public static void WorkWithT<T>() where T : new()
{
Generic<T> g = new Generic<T>();
T obj = g.Create();
Console.WriteLine(g.IsArray());
}
var method = typeof(Program).GetMethod("WorkWithT").MakeGenericMethod(field.FieldType);
// Single reflection use. Inside WorkWithT no reflection is used.
method.Invoke(null, null);