C # Dynamic extends object

Is it possible to expand an existing object?

I have a code

var record = new { id, name }; 

and list of anonymous objects

 var list = new List<object>(){ object1, object2 }; 

Can I add them later to the object? Somehow how

 foreach (var o in list) { record.add(o); } 

that I will get it as a result

 var record = new { id, name, object1, object2 }; 
+4
source share
3 answers

In short, no. At least not with anonymous types. There are two approaches here; dynamic can give you what you want, but is inconvenient for combining. In addition, the main property package is even just Dictionary<string,object> . The only difference is that:

 obj.id 

becomes

 obj["id"] 

However, there is a more fundamental problem when trying to combine a list (each of which is largely anonymous) with properties in one step. You can do this to bind data using custom property models , but it's ... complicated.

+2
source

What you can do is create a class extension. It is not possible to add new methods at runtime, but you can do something like this:

 public class OneClass { private List<object> items; public List<object> Items { get { return items; } } public void AddOne(object item) { items.Add(item); } } 

if you want to extend the behavior of this class, you can write an extension class. Like this:

 public static class OneClassExtensions { public void AddMany(this OneClass self, params object[] items) { foreach(object item in items) { self.Items.Add(item); } } } 

In this way, you can call this extension method from OneClass objects:

 OneClass obj = new OneClass(); obj.AddOne("hello"); obj.AddMany("Hello", "world"); // Extension method 

The following rules apply:

  • The extension class must have the `static 'modifier
  • you need to prefix `this' with the first argument. This argument will be the object itself.
  • To use this extension class in your code, you must use the namespace that this extension class contains, for example, `use Some.Namespace.That.Has.An.Extension 'in each .cs file in which you want to use extension methods.
+1
source

Since .net4 you can use ExpandoObject to do such things.

For instance:

  var objs = new List<ExpandoObject>(); for (var i = 0; i < 10; i++) { dynamic eObj = new ExpandoObject(); eObj.Property = i; objs.Add(eObj); } foreach (dynamic obj in objs) { obj.Property2 = "bubuValue" + obj.Property; obj.Property3 = "bubuValue" + obj.Property2; } foreach (dynamic obj in objs) { Console.WriteLine(obj.Property3); } 
0
source

Source: https://habr.com/ru/post/1336135/


All Articles