interface property copy in c#

后端 未结 8 2207
一生所求
一生所求 2021-02-07 08:13

I\'ve been working with C# for many years now, but just come across this issue that\'s stumping me, and I really don\'t even know how to ask the question, so, to the example!

相关标签:
8条回答
  • 2021-02-07 09:07

    Here's one way to do it that has nothing to do with interfaces:

    public static class ExtensionMethods
    {
        public static void CopyPropertiesTo<T>(this T source, T dest)
        {
            var plist = from prop in typeof(T).GetProperties() where prop.CanRead && prop.CanWrite select prop;
    
            foreach (PropertyInfo prop in plist)
            {
                prop.SetValue(dest, prop.GetValue(source, null), null);
            }
        }
    }
    
    class Foo
    {
        public int Age { get; set; }
        public float Weight { get; set; }
        public string Name { get; set; }
        public override string ToString()
        {
            return string.Format("Name {0}, Age {1}, Weight {2}", Name, Age, Weight);
        }
    }
    
    static void Main(string[] args)
    {
         Foo a = new Foo();
         a.Age = 10;
         a.Weight = 20.3f;
         a.Name = "Ralph";
         Foo b = new Foo();
         a.CopyPropertiesTo<Foo>(b);
         Console.WriteLine(b);
     }
    

    In your case, if you only want one set of interface properties to copy you can do this:

    ((IAddress)home).CopyPropertiesTo<IAddress>(b);
    
    0 讨论(0)
  • 2021-02-07 09:07

    You could have a constructor on each class taking an IAddress and have implemented members populated within.

    eg

    public WorkAddress(Iaddress address)
    {
        Line1 = IAddress.Line1;
        ...
    }
    

    For maintainability use reflection to get property names.

    HTH,

    Dan

    0 讨论(0)
提交回复
热议问题