使用 C# 匿名类型 [英] Working with C# Anonymous Types
问题描述
我正在调用一个方法,该方法返回一个包含 c# 匿名类型对象的 List 变量.例如:
I am calling a method that returns a List variable that contains a c# Anonymous Type objects. For example:
List<object> list = new List<object>();
foreach ( Contact c in allContacts ) {
list.Add( new {
ContactID = c.ContactID,
FullName = c.FullName
});
}
return list;
如何在我正在处理的代码中引用这种类型的属性,例如
How do I reference this type properties in the code I am working on like for example
foreach ( object o in list ) {
Console.WriteLine( o.ContactID );
}
我知道我的样本是不可能的,我这样写只是为了说明我需要准确识别匿名类型的每个属性.
I know that my sample is not possible, I have only wrote that way to say that I need to identify each property of the anonymous type exactly.
谢谢!
解决方案:
不仅仅是一个答案是正确的和/或提出了一个可行的解决方案.我最终使用了 Greg 答案的选项 3.我学到了一些关于 .NET 4.0 中的 dynamic
非常有趣的东西!
Not just one of the answer is correct and/or suggest a working solution. I have ended up to using Option 3 of Greg answer. And I learned something very interesting regarding the dynamic
in .NET 4.0!
推荐答案
你不能返回一个匿名类型的列表,它必须是一个 object
的列表.因此,您将丢失类型信息.
You can't return a list of an anonymous type, it will have to be a list of object
. Thus you will lose the type information.
选项 1
不要使用匿名类型.如果您尝试在多个方法中使用匿名类型,请创建一个真正的类.
Option 1
Don't use an anonymous type. If you are trying to use an anonymous type in more than one method, then create a real class.
选项 2
不要将您的匿名类型向下转换为 object
.(必须是一种方法)
var list = allContacts
.Select(c => new { c.ContactID, c.FullName })
.ToList();
foreach (var o in list) {
Console.WriteLine(o.ContactID);
}
选项 3
使用动态关键字.(需要 .NET 4)
Option 3
Use the dynamic keyword. (.NET 4 required)
foreach (dynamic o in list) {
Console.WriteLine(o.ContactID);
}
选项 4
使用一些肮脏的反射.
Option 4
Use some dirty reflection.
这篇关于使用 C# 匿名类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!