用C#匿名类型类型

2023-09-09 21:02:47 作者:没良心的孩纸

我打电话返回包含一个C#匿名类型的对象列表变量的方法。例如:

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;

我如何在code我的工作例如像

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.

谢谢!

解决方案

不只是答案是正确的和/或提出一个可行的解决方案。我已经结束了,使用了格雷格的答案选项3。我学到了一些东西很有意思的关于在.NET 4.0中的动态

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!

推荐答案

您不能返回匿名类型的列表,它必须是对象。因此,你将失去类型信息。

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 不要向下转换匿名类型对象。 (必须是一种方法)

Option 2 Don't downcast your anonymous type to object. (must be in one method)

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.

 
精彩推荐
图片推荐