Rya*_*ker 8 c# generics reflection runtime dynamic
我有一个问题涉及使用在运行时已知的类型参数调用类的泛型方法.
具体来说,代码如下所示:
FieldInfo[] dataFields = this.GetType().GetFields( BindingFlags.Public | BindingFlags.Instance );
// data is just a byte array used internally in DataStream
DataStream ds = new DataStream( data );
foreach ( FieldInfo field in dataFields )
{
Type fieldType = field.FieldType;
// I want to call this method and pass in the type parameter specified by the field's type
object objData = ( object ) ds.Read<fieldType>();
}
Run Code Online (Sandbox Code Playgroud)
Read()函数如下所示:
public T Read() where T : struct
Run Code Online (Sandbox Code Playgroud)
该函数的目的是返回从字节数组中读取的数据.
有没有办法在运行时调用泛型方法?
Lee*_*Lee 12
处理此问题的最简单方法是使用单个Type参数进行Read函数的非泛型重载:
public object Read(Type t)
Run Code Online (Sandbox Code Playgroud)
然后让通用版本调用非泛型版本:
public T Read<T>() where T : struct
{
return (T)Read(typeof(T))
}
Run Code Online (Sandbox Code Playgroud)
您需要构建一个methodinfo并调用Read方法:
MethodInfo method = typeof(DataStream).GetMethod("Read");
MethodInfo generic = method.MakeGenericMethod(fieldType);
object objData = generic.Invoke(ds, null);
Run Code Online (Sandbox Code Playgroud)