编译器优化匿名类型

Pan*_*cus 7 c# anonymous-types .net-4.0 compiler-optimization

好的,我知道这是一个黑客,但这是一个小小的数据操作项目,我想玩.;-)

我一直认为编译器会检查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 });
Run Code Online (Sandbox Code Playgroud)

我现在可以做一些有趣的事情,比如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});
Run Code Online (Sandbox Code Playgroud)

现在当我做bigData2.Except(bigData1); 编译器抱怨:

Instance argument: cannot convert from
'System.Data.EnumerableRowCollection<AnonymousType#1>' to
'System.Linq.IQueryable<AnonymousType#2>'
Run Code Online (Sandbox Code Playgroud)

为什么?属性太多,因此编译器决定优化它是不值得的?

谢谢!

Swa*_*nny 2

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