Enumerate and copy properties from one object to another object of same type

前端 未结 5 912
故里飘歌
故里飘歌 2021-01-18 17:06

I use a third party control which exports some data to different formats. The control has a property ExportSettings. But it is read-only.

I\'ve to manua

5条回答
  •  情歌与酒
    2021-01-18 17:11

    Try reflection-based cloning:

    private object CloneObject(object o)
    {
        Type t = o.GetType();
        PropertyInfo[] properties = t.GetProperties();
    
        Object p = t.InvokeMember("", System.Reflection.BindingFlags.CreateInstance, 
            null, o, null);
    
        foreach (PropertyInfo pi in properties)
        {
            if (pi.CanWrite)
            {
                pi.SetValue(p, pi.GetValue(o, null), null);
            }
        }
    
        return p;
    }
    

提交回复
热议问题