gpt4 book ai didi

c# - FastMember ObjectReader 返回 0 个结果

转载 作者:行者123 更新时间:2023-11-30 20:33:36 26 4
gpt4 key购买 nike

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

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 方法拒绝为该读取器创建空行。

如果可以,请尝试使用具体类:

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

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

//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 的方法:

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

另请注意,这比其他方法风险更大,因为可以创建包含混合项目类型的列表。 Fastmember 需要列表中的每个项目都是完全相同的类型,像下面这样的东西会导致异常:

//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" } };

关于c# - FastMember ObjectReader 返回 0 个结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40020589/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com