copy a class, C#

后端 未结 12 1762
失恋的感觉
失恋的感觉 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:46

    Some reasonable solutions here serializing is a valid way to go about it as well as a clone method for each class.. Whipped this up and It seems to work for the few tests i did on it

    using System.Reflection; using System.Text.StringBuilder();
    
    public static T CopyClass2(T obj){
        T objcpy = (T)Activator.CreateInstance(typeof(T));
        obj.GetType().GetProperties().ToList()
        .ForEach( p => objcpy.GetType().GetProperty(p.Name).SetValue(objcpy, p.GetValue(obj)));
        return objcpy;
    

    }

    And here is the more verbose version I suppose, above suggests you understand Lambda Expressions which isn't common. If you respect readability (Which is totally valid) more I would use below

    public static T CopyClass(T obj)
    {
        T objcpy = (T)Activator.CreateInstance(typeof(T));
        foreach (var prop in obj.GetType().GetProperties())
        {
            var value = prop.GetValue(obj);
            objcpy.GetType().GetProperty(prop.Name).SetValue(objcpy, value);
        }
        return objcpy;
    

    }

    Use this method to list out property's to see if it copied to new reference.. simple it does not list properties of none primitives(structured types).. so you will get a class name

    public static string ListAllProperties(T obj)
    {
            StringBuilder sb = new System.Text.StringBuilder();
            PropertyInfo[] propInfo = obj.GetType().GetProperties();
            foreach (var prop in propInfo)
            {
                var value = prop.GetValue(obj) ?? "(null)";
                sb.AppendLine(prop.Name + ": " + value.ToString());
            }
            return sb.ToString();
    }
    

提交回复
热议问题