gpt4 book ai didi

c# - 匿名类型的编译器优化

转载 作者:太空狗 更新时间:2023-10-29 20:29:15 25 4
gpt4 key购买 nike

好的 好的,我知道这是一个 hack,但这是针对一个小型数据处理项目的,我想尝试一下。 ;-)

我一直认为编译器会检查 C# 程序中使用的所有匿名类型,如果属性相同,它只会在幕后创建一个类。

假设我想从我拥有的一些类型化数据集中创建一个匿名类型:

var smallData1 = new smallData1().GetData().Select(
x => new { Name = x.NAME, x.ADDRESS, City = x.CITY, State = x.STATE,
Zip = x.ZIP, Country = x.COUNTRY, ManagerName = x.MANAGER_NAME,
ManagerID = x.MANAGER_ID });

var smallData2 = new smallData2().GetData().Select(
x => new { x.Name, x.ADDRESS, x.City, x.State, x.Zip, x.Country,
x.ManagerName,x.ManagerID });

我现在可以做一些有趣的事情,比如 smallData2.Except(smallData1); 等,而且一切正常。

现在,如果我有一对更大的匿名类型怎么办:

var bigData1 = new BigAdapter1().GetData().Select(
x => new { x.FirstName, x.LastName, x.Address, x.City, x.State,
x.Zip, x.Country, x.Phone, x.Email, x.Website, x.Custom1, x.Custom2,
x.Custom3, x.Custom4, x.Custom5, x.Custom6, x.Custom7, x.Custom8, x.Custom9,
x.Custom10, x.Custom11, x.Custom12, x.Custom13, x.Custom14, x.Custom15,
x.Custom16, x.Custom17, x.Custom18, x.Custom19, x.Custom20, x.Custom21,
x.Custom22, x.Custom23, x.Custom24, x.Custom25, x.Custom26, x.Custom27,
x.Custom28, x.Custom29});

var bigData2 = new BigAdapter2().GetData().Select(
x => new { x.FirstName, x.LastName, x.Address, x.City, x.State, x.Zip,
x.Country, x.Phone, x.Email, x.Website, x.Custom1, x.Custom2, x.Custom3,
x.Custom4, x.Custom5, x.Custom6, x.Custom7, x.Custom8, x.Custom9, x.Custom10,
x.Custom11, x.Custom12, x.Custom13, x.Custom14, x.Custom15, x.Custom16,
x.Custom17, x.Custom18, x.Custom19, x.Custom20, x.Custom21, x.Custom22,
x.Custom23, x.Custom24, x.Custom25, x.Custom26, x.Custom27,
x.Custom28, x.Custom29});

现在,当我执行 bigData2.Except(bigData1); 时,编译器会提示:

Instance argument: cannot convert from
'System.Data.EnumerableRowCollection<AnonymousType#1>' to
'System.Linq.IQueryable<AnonymousType#2>'

为什么?属性太多,所以编译器认为不值得优化?

谢谢!

最佳答案

是的。它不是属性的数量。您如何确定您的适配器返回的数据类型完全相同?

关于c# - 匿名类型的编译器优化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3314668/

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