除了对LINQ查询,你如何在C#中使用匿名类型? [英] Other than for LINQ queries, how do you use anonymous types in C#?
问题描述
我一直在试图加快速度的一些C#中的新功能,而且我还没有机会使用匿名类型的其中之一。
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.
我理解的使用,因为它涉及到LINQ查询我看着的这个SO帖子这问过类似的问题。大部分时间我已经看到了网上的例子都涉及到LINQ查询,这是很酷。我看到一些有点做作的例子太多,但算不上什么,我看到了很多的价值。
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?
推荐答案
通过一点反思,你可以把匿名类型到字典<字符串对象> ;;罗伊Osherove博客他的技术为这个在这里:的 http://weblogs.asp.net/rosherove/archive/2008/03/11/turn-anonymous-types-into-idictionary-of-values.aspx
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
雅各木匠使用匿名类型的一种方式类似于对象初始化语法来初始化不可变对象:的 http://jacobcarpenter.wordpress.com/2007/11/19/named-parameters-part-2/
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/
匿名类型可以作为一种方式让更容易阅读的别名被遍历了的foreach
语句。 (不过,说实话,这真的没什么比标准使用匿名类型的使用的 LINQ到对象),例如:
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);
虽然不是这短短的样本太大起色,如果的foreach
循环是更长的时间,参考 ID
和名称
可能会提高可读性。
While there's not much improvement in this short sample, if the foreach
loop were longer, referring to ID
and Name
might improve readability.
这篇关于除了对LINQ查询,你如何在C#中使用匿名类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!