简体   繁体   中英

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>

Now, how can I add, lets say, ExampleBool property into every object inside that List<Example> , without implementing it directly into Example class?

C# is statically typed language. 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. But you will lose IntelliSense, performance will suffer, and you will have to create each object from scratch:

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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