调用在运行时确定的类型参数的通用函数 [英] Calling a generic function with a type parameter determined at runtime

查看:109
本文介绍了调用在运行时确定的类型参数的通用函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



具体而言,代码如下所示:

  
FieldInfo [] dataFields = this.GetType()。GetFields(BindingFlags.Public | BindingFlags.Instance);

//数据只是DataStream内部使用的一个字节数组
DataStream ds = new DataStream(data);

foreach(dataFields中的FieldInfo字段)
{
类型fieldType = field.FieldType;

//我想调用此方法并传入由字段类型指定的类型参数
object objData =(object)ds.Read< fieldType>();
}

Read()函数如下所示:

  
public T Read()其中T:struct

此函数的目的是返回从字节数组读取的数据。



有没有办法在运行时像这样调用泛型方法?

解决方案

最简单的方法是使用单个Type参数对Read函数进行非泛型重载:

  public object Read(type t)

然后通用版本调用非泛型版本:

  public T阅读< T>()其中T:struct 
{
return(T)Read(typeof(T))
}


I have a question involving calling a class's generic method with a type parameter that is known at runtime.

In specific, the code looks like so:


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>();
}

The Read() function looks like so:


public T Read() where T : struct

This function's purpose is to return data read from a byte array.

Is there any way to call a generic method at runtime like this?

解决方案

The easiest way to handle this would be to make a non-generic overload of the Read function with a single Type parameter:

public object Read(Type t)

And then have the generic version call the non-generic version:

public T Read<T>() where T : struct
{
    return (T)Read(typeof(T))
}

这篇关于调用在运行时确定的类型参数的通用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆