Other than for LINQ queries, how do you use anonymous types in C#?

徘徊边缘 提交于 2020-01-01 05:29:29

问题


I've been trying to get up to speed on some of the newer features in C# and one of them that I haven't had occasion to use is anonymous types.

I understand the usage as it pertains to LINQ queries and I looked at this SO post which asked a similar question. Most of the examples I've seen on the net are related to LINQ queries, which is cool. I saw some somewhat contrived examples too but not really anything where I saw a lot of value.

Do you have a novel use for anonymous types where you think it really provides you some utility?


回答1:


With a bit of reflection, you can turn an anonymous type into a Dictionary<string, object>; Roy Osherove blogs his technique for this here: http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx

Jacob Carpenter uses anonymous types as a way to initialize immutable objects with syntax similar to object initialization: http://jacobcarpenter.wordpress.com/2007/11/19/named-parameters-part-2/

Anonymous types can be used as a way to give easier-to-read aliases to the properties of objects in a collection being iterated over with a foreach statement. (Though, to be honest, this is really nothing more than the standard use of anonymous types with LINQ to Objects.) For example:

Dictionary<int, string> employees = new Dictionary<int, string>
{
    { 1, "Bob" },
    { 2, "Alice" },
    { 3, "Fred" },
};

// standard iteration
foreach (var pair in employees)
    Console.WriteLine("ID: {0}, Name: {1}", pair.Key, pair.Value);

// alias Key/Value as ID/Name
foreach (var emp in employees.Select(p => new { ID = p.Key, Name = p.Value }))
    Console.WriteLine("ID: {0}, Name: {1}", emp.ID, emp.Name);

While there's not much improvement in this short sample, if the foreach loop were longer, referring to ID and Name might improve readability.




回答2:


ASP.NET MVC routing uses these objects all over the place.




回答3:


Occasionally I suspect it may be useful to perform something which is like a LINQ query, but doesn't happen to use LINQ - but you still want a projection of some kind. I don't think I'd use anonymous types in their current form for anything radically different to LINQ projections.

One thing I would like to see is the ability to create "named" types with simple declarations, which would generate the properties and constructor in the same way as for anonymous types, as well as overriding Equals/GetHashCode/ToString in the same (useful) way. Those types could then be converted into "normal" types when the need to add more behaviour arose.

Again, I don't think I'd use it terribly often - but every so often the ability would be handy, particularly within a few methods of a class. This could perhaps be part of a larger effort to give more support to immutable types in C# 5.




回答4:


To add to what Justice said, ASP.Net MVC is the first place I've seen these used in interesting and useful ways. Here's one example:


Html.ActionLink("A Link", "Resolve", new { onclick = "someJavascriptFn();" })

ASP.Net MVC uses anonymous types like this to add arbitrary attributes to HTML elements. I suppose there's a number of different ways you could accomplish the same thing, but I like the terse style of anonymous types, it gives things more of a dynamic language feel.




回答5:


The biggest use for anonymous types is LINQ, in fact that's why it was created.

I guess one reason for an anonymous type outside of linq is to create a temporary struct-like object, e.g.:

var x = new { a = 1, b = 2 };

That may make your life a little easier in some situations.




回答6:


I've used them for doing templated emails as they are great if you're using reflection and generics.

Some info can be found here: http://www.aaron-powell.com/blog.aspx?id=1247



来源:https://stackoverflow.com/questions/168150/other-than-for-linq-queries-how-do-you-use-anonymous-types-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!