首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >FastMember ObjectReader返回0的结果

FastMember ObjectReader返回0的结果
EN

Stack Overflow用户
提问于 2016-10-13 12:07:48
回答 1查看 3.1K关注 0票数 2

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

代码语言:javascript
复制
List<object> list = new List<object>() { new { Number = 500 } };
DataTable table = new DataTable();
using (var reader = ObjectReader.Create(list))
{
    table.Load(reader);
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-10-13 12:37:41

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

如果可以的话,可以使用一个具体的类来尝试:

代码语言:javascript
复制
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);
        }
    }
}

编辑:实际上,完全能够访问这些属性,但是泛型列表(对象)的类型使它无法看到它们。如果您可以提供一个具有实际运行时类型的IEnumerable,那么它也可以工作:

代码语言:javascript
复制
//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:

代码语言:javascript
复制
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);
}

还请注意,这比其他方法风险更大,因为可以创建具有混合项类型的列表。Fast员需要列表中的每一项都具有完全相同的类型,如下所示将导致异常:

代码语言:javascript
复制
//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" } };
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40020589

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档