简体   繁体   中英

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

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.

我将枚举对象的属性(a.GetType()。GetProperties()),在内置类型,结构和类之间进行转换,并使用ExpandoObject构建动态对象。

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

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);
     }
  }
}

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 (eg Java) allows to invoke static method through object instead of type.

for more details please visit enter link description here

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