从动态列表中调用扩展方法

时间:2019-02-20 14:16:10

标签: c# dynamic reflection extension-methods

我正在使用反射创建一个类型...

Type type = Type.GetType("Book");

然后我动态地调用一个方法...

MethodInfo method = typeof(DataHelper).GetMethod("GetTableData");
MethodInfo generic = method.MakeGenericMethod(type);
var parameters = new object[] {...};
dynamic data = generic.Invoke(this, parameters);

该方法返回数据,看起来像这样……

public static IEnumerable<T> GetTableData<T>(parameters)
{
...
}

从动态数据中,我想将其转换为列表,然后调用扩展方法以将列表转换为DataTable。

我尝试了以下操作,但在调用.ToDataTable时失败:

var x = Enumerable.ToList(data);
x.ToDataTable().BulkCopyDataTable(settings, booName);

我也尝试过:

var tl = GetTypedList(type);
            foreach (var d in x)
            {
                tl.Add(d);
            }

var y = tl.ToDataTable(); // compilaer error.

private static IList GetTypedList(Type t)
        {
            var listType = typeof(List<>);
            var constructedListType = listType.MakeGenericType(t);
            var instance = Activator.CreateInstance(constructedListType);
            return (IList) instance;
        }

我要调用的扩展方法是:

public static DataTable ToDataTable<T>(this IList<T> data)
        {
            var properties = TypeDescriptor.GetProperties(typeof(T));
            var table = new DataTable();
            foreach (PropertyDescriptor prop in properties)
                table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);

            foreach (var item in data)
            {
                var row = table.NewRow();
                foreach (PropertyDescriptor prop in properties)
                    row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
                table.Rows.Add(row);
            }


            return table;
        }

有什么指针可以指出问题所在吗?

0 个答案:

没有答案
相关问题