Generic C# Copy Constructor

前端 未结 5 1380
再見小時候
再見小時候 2021-01-31 10:55

What would be the best way to write a generic copy constructor function for my c# classes? They all inherit from an abstract base class so I could use reflection to map the prop

5条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 11:18

    Here's a constructor that I'm using. Note that this is a shallow constructor, and rather simplistic, due to the nature of my base class. Should be good enough to get you started.

    public partial class LocationView : Location
    {
        public LocationView() {}
    
        // base class copy constructor
        public LocationView(Location value) {
            Type t = typeof(Location);
            PropertyInfo[] properties = t.GetProperties();
            foreach (PropertyInfo pi in properties)
            {
                pi.SetValue(this, pi.GetValue(value, null), null);
            }
        }
        public Quote Quote { get; set; }
    }
    

提交回复
热议问题