简体   繁体   English

在C#中检索匿名对象的属性

[英]Retrieving Anonymous Object's Property in C#

I have the following code 我有以下代码

using System;
using System.Collections.Generic;

public class Test
{
    public static void Main()
    {
        List<object> list = new List<object>();
        list.Add(new {
            Value = 0
        });
        //Console.WriteLine(list[0].Value);
    }
}

Is there a simple way to write the commented line of code without causing a compile time error? 有没有一种简单的方法来编写注释的代码行而不会导致编译时错误? I know I could resort to using the dynamic keyword or implementing an extension method for the Object class that uses Reflection, but is there maybe another more acceptable way? 我知道我可以求助于使用dynamic关键字或为使用Reflection的Object类实现扩展方法,但是也许还有另一种更可接受的方法吗?

The goal is the avoid creating a class since its only purpose would be to store data. 目标是避免创建类,因为它的唯一目的是存储数据。 But at the same time still be able to retrieve the data later on in the program. 但与此同时,稍后仍可以在程序中检索数据。 This code will eventually end up in a web method which is why I want it to be dynamic / anonymous in the first place. 这段代码最终将以Web方法结尾,这就是为什么我首先希望它是动态的/匿名的。 All of the objects would end up having the same properties, as they would be storing values stored in tables, but the values are needed later for other calculations. 所有对象最终将具有相同的属性,因为它们将存储存储在表中的值,但是稍后需要这些值进行其他计算。

Is there a simple way to write the commented line of code without causing a compile time error? 有没有一种简单的方法来编写注释的代码行而不会导致编译时错误?

Not with the way you've declared the list. 与声明列表的方式不同。 If your list will contain only objects of that anonymous type, you could use an array initializer and convert it to a List<{anonymous type}> : 如果您的列表仅包含该匿名类型的对象,则可以使用数组初始化器,并将其转换为List<{anonymous type}>

var list = (new [] {
         new { Value = 0 }
     }).ToList();
Console.WriteLine(list[0].Value);

The nice thing is that you can add to the list easily, since anonymous types with the same properties are merged into one type by the compiler: 令人高兴的是,您可以轻松地将其添加到列表中,因为具有相同属性的匿名类型将由编译器合并为一种类型:

list.Add(new {Value = 1});

Per Servy's comment, a method to avoid an array creation would just be: 根据Servy的评论,避免数组创建的方法将是:

public static List<T> CreateList<T>(params T[] items)
{
     return new List<T>(items);
}

usage: 用法:

var list = CreateList(new { Value = 0 });

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

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