简体   繁体   English

在列表中的类对象中添加属性

[英]Add a property into class object within a list

I have a list with class object. 我有一个带有类对象的列表。 I would like to know how to add a property into it later on, without implementing the property directly into that class from the beginning. 我想知道以后如何在其中添加属性,而不是从一开始就直接在该类中实现该属性。

public class Example{

   public int ExampleInt {get; set;}
   public string ExampleString {get; set;}
   public double ExampleDouble {get; set;}
}

I have a list of Example like: List<Example> 我有一个Example列表,例如: List<Example>

Now, how can I add, lets say, ExampleBool property into every object inside that List<Example> , without implementing it directly into Example class? 现在,如何将ExampleBool属性添加到List<Example>每个对象中,而不直接将其实现到Example类中?

C# is statically typed language. C#是静态类型的语言。 You cannot dynamically add or remove class members. 您不能动态添加或删除类成员。 But you can create new anonymous class which will have any properties you want: 但是您可以创建新的匿名类,该类将具有您想要的任何属性:

var examples = new List<Example>();
var result = from e in examples
             select new {
                 e.ExampleInt,
                 e.ExampleString,
                 e.ExampleDouble,
                 ExampleBoolean = true
             };

In some cases it might be helpful to use dynamic object instead of statically typed classes. 在某些情况下,使用动态对象而不是静态类型的类可能会有所帮助。 Take a look on ExpandoObject - it allows you to dynamically add and remove members at runtime. 看一下ExpandoObject-它允许您在运行时动态添加和删除成员。 But you will lose IntelliSense, performance will suffer, and you will have to create each object from scratch: 但是您将失去IntelliSense,性能将受到影响,并且您将不得不从头开始创建每个对象:

var examples = new List<dynamic>
{
    new ExpandoObject(), // initially it does not have any properties
    new ExpandoObject()
};

for (int i = 0; i < examples.Count; i++)
{
    examples[i].ExampleInt = i;
    // etc
}

for (int i = 0; i < examples.Count; i++) // we add new property
    examples[i].ExampleBoolean = i % 2 == 0;

foreach(var example in examples)
    Console.WriteLine($"{example.ExampleInt} {example.ExampleBoolean}");

It's not possible in a standard way, but you can create inheritor 这是不可能的,但是您可以创建继承者

public class ExampleWithBool { public bool ExampleBoolean {get; set;}}

Also, anonymous class (see Sergey's answer). 另外,匿名类(请参见Sergey的答案)。

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

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