Clone derived class from base class method

后端 未结 7 2219
萌比男神i
萌比男神i 2021-02-08 17:09

I have an abstract base class Base which has some common properties, and many derived ones which implement different logic but rarely have additional fields.

<
7条回答
  •  无人及你
    2021-02-08 18:11

    Found this question while trying to solve this exact problem, had some fun with LINQPad while at it. Proof of concept:

    void Main()
    {
        Person p = new Person() { Name = "Person Name", Dates = new List() { DateTime.Now } };
    
        new Manager()
        {
            Subordinates = 5
        }.Apply(p).Dump();
    }
    
    public static class Ext
    {
        public static TResult Apply(this TResult result, TSource source) where TResult: TSource
        {
            var props = typeof(TSource).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (var p in props)
            {
                p.SetValue(result, p.GetValue(source));
            }
    
            return result;
        }
    }
    
    class Person 
    {
        public string Name { get; set; }
        public List Dates { get; set; }
    }
    
    class Manager : Person
    {
        public int Subordinates { get; set; }
    }
    

提交回复
热议问题