简体   繁体   English

是否可以将方法附加到C#匿名类型?

[英]Is it possible to attach methods to C# anonymous types?

It would be desirable to be able to provide eg comparison functions (ie with lambdas) for an anonymous type, so that they can be sorted by a set of criteria. 期望能够为匿名类型提供例如比较函数(即,使用lambdas),以便可以通过一组标准对它们进行排序。 Is that possible in C#? 这可能在C#中吗?

No, just make a regular class instead. 不,只是做一个普通的课程。

Possible related: Can a C# anonymous class implements an interface? 可能相关: C#匿名类可以实现接口吗?

Lambdas are implicitly convertable to System.Comparison`1: Lambdas可以隐式转换为System.Comparison .1:

var anons = (new[] {new {a = 3}, new {a = 4}, new {a = 2}}).ToList();
anons.Sort((x, y) => (x.a - y.a));

You can also use the LINQ OrderBy extension method to sort anonymous types. 您还可以使用LINQ OrderBy扩展方法对匿名类型进行排序。

var anons = new[] {new {a = 3}, new {a = 4}, new {a = 2}};
var sorted = anons.OrderBy(s => s.a);

Yes. 是。 You must declare the type of the comparison function: 您必须声明比较函数的类型:

var anon = new {comparator = (Func<string, int>) (s => s.Length)};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM