FastMember ObjectReader返回0个结果 [英] FastMember ObjectReader Returns 0 results

查看:446
本文介绍了FastMember ObjectReader返回0个结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用FastMember库将对象列表转换为dataTable,但它返回空对象,所以任何人都可以帮我解决这个问题。

I am using FastMember Library to convert List of objects to a dataTable but it returns empty object so could anyone help me to resolve this issue

List<object> list = new List<object>() { new { Number = 500 } };
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(list))
{
    table.Load(reader);
}


推荐答案

显然,Fastmember不能枚举匿名对象的属性。因此,创建的数据读取器没有列,DataTable.Load方法拒绝为此读者创建空行。

Apparently, Fastmember is not able to enumerate the properties off of anonymous objects. Therefore, the created data reader has no columns and DataTable.Load method refuses to create empty rows for this reader.

如果可以,请尝试一个具体的类: p>

Try it with a concrete class if you can:

class Thingy
{
    public int Number { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        List<Thingy> list = new List<Thingy>() { new Thingy { Number = 500 } };
        DataTable table = new DataTable();
        using (var reader = ObjectReader.Create(list))
        {
            table.Load(reader);
        }
    }
}

编辑: / strong>实际上,Fastmember完全能够访问这些属性,但是通用List(对象)的类型阻止它们看到它们。如果您可以提供实际运行时类型的IEnumerable,它也应该可以工作:

Actually, Fastmember is perfectly capable of accessing those properties, but the type of the generic List (object) prevents it from seeing them. It should also work if you can provide an IEnumerable with the actual runtime type:

//This creates a "strongly" typed list, instead of List<object>:
var list = new[] { (new { Number = 500 }) }.ToList();

DataTable table = new DataTable();
using (var reader = ObjectReader.Create(list))
{
    table.Load(reader);
}

编辑2:还有另一种方法通过使用构造函数将类型信息传递给Fastmember:

Edit 2: There is yet another way to pass the type information to Fastmember by using the constructor:

List<object> list = new List<object> { new { Number = 500 } };

DataTable table = new DataTable();

// Note that type information is derived directly from the first object in the list, 
// so try not to pass an empty one :)
using (var reader = new ObjectReader(list[0].GetType(), list, null))
{
    table.Load(reader);
}

另请注意,这比其他方法更危险,因为可以创建具有混合项目类型的列表。快速成员需要列表中的每个单个项目都是完全相同的类型,类似以下内容会导致异常:

Also note that this is riskier than the other approaches because it is possible to create a list with mixed item types. Fastmember needs every single item in the list to be of the exact same type and something like the following will cause an exception:

//These two items are not of the same type. Look carefully at the "Extra" property:
List<object> list = new List<object> { new { Number = 500, Extra = true }, new { Number = 500, Extra = "Boom" } };

这篇关于FastMember ObjectReader返回0个结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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