我有一个问题,涉及使用在运行时已知的类型参数调用类的泛型方法。使用在运行时确定的类型参数调用泛型函数
在具体的代码看起来像这样:
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>();
}
的read()函数看起来像这样:
public T Read() where T : struct
该功能的目的是返回从字节数组中读取数据。
有没有什么办法像这样在运行时调用泛型方法?
感谢您的回复,我从来没有考虑过这么简单的设计变更。 – 2009-09-21 18:26:33
我的问题并没有像OP问题那样看起来像,但是你完全证明了我需要知道的东西。谢谢! – KennyZ 2012-05-20 13:39:59