copy a class, C#

后端 未结 12 1789
失恋的感觉
失恋的感觉 2020-12-03 10:13

Is there a way to copy a class in C#? Something like var dupe = MyClass(original).

12条回答
  •  醉酒成梦
    2020-12-03 10:45

    If your class has just got properties, you could do something like this:

    SubCentreMessage actual;
    actual = target.FindSubCentreFullDetails(120); //for Albany
    SubCentreMessage s = new SubCentreMessage();
    
    //initialising s with the same values as 
    foreach (var property in actual.GetType().GetProperties())
    {
        PropertyInfo propertyS = s.GetType().GetProperty(property.Name);
        var value = property.GetValue(actual, null);
        propertyS.SetValue(s, property.GetValue(actual, null), null);
    }
    

    If you have fields and methods, I am sure you can recreate them in new class using reflections. Hope this helps

提交回复
热议问题