C# - How to create a dynamic object from a static object?

自古美人都是妖i 提交于 2019-12-25 06:14:31

问题


Suppose there is a static object with type A.

class A
{
    public string b;
    public int c;
    public bool d;
    public A e;
    .
    .
    .
}

A a = new A(){
    b = "string",
    c = 12,
    d = true
    e = new A(){
            b = "another string",
            c = 23
        }
};

I want to deep clone this object into a dynamic object with all of its properties.


回答1:


I would enumerate the properties of the object (a.GetType().GetProperties()), destinguish between built-in types, structs and classes and use ExpandoObject to build the dynamic object.




回答2:


The easiest way is to serialize the class into a json and deserialize it into a dynamic object.

Use Json.net:

        A a = new A()
        {
            b = "string",
            c = 12,
            d = true,
            e = new A()
            {
                b = "another string",
                c = 23
            }
        };

        var json = JsonConvert.SerializeObject(a); // create a json 
        dynamic newObj = JsonConvert.DeserializeObject(json);// create a dynamic object



回答3:


Build a copy constructor:

class A   //<-- this class is static?????
{
  public string b;
  public int c;
  public bool d;
  public A e;

  public A() { }  // add default constructor

  public A(A a){
     b = a.b;
     c = a.c;
     d = a.d;
     if ( a.e != null ) {
        e = new A(a.e);
     }
  }
}



回答4:


In C#4.0, we have the concept of dynamic, but how to create a dynamic object from a static static object?

Below code will generate exception at run time. The dynamic object is from C# class, but it could be object from other languages through Dynamic Language Runtime (DLR). The point is not how to invoke static method, but how to invoke static method of dynamic object which could not be created in C# code.

class Foo { public static int Sum(int x, int y) { return x + y; } }

class Program {

static void Main(string[] args)
{
    dynamic d = new Foo();
    Console.WriteLine(d.Sum(1, 3));

}

}

dynamic type is invented as bridge between C# and other programming language. There is some other language (e.g. Java) allows to invoke static method through object instead of type.

for more details please visit enter link description here



来源:https://stackoverflow.com/questions/23156815/c-sharp-how-to-create-a-dynamic-object-from-a-static-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!