interface property copy in c#

后端 未结 8 2210
一生所求
一生所求 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 08:57

    There's no one-liner for this.

    If you do it a lot, you could look into some form of code generation, perhaps using T4 templates and Reflection.

    BTW COBOL has a statement for this: MOVE CORRESPONDING HOME TO WORK.

    0 讨论(0)
  • 2021-02-07 08:58

    I don't believe there's a language ready solution for this (all the properties would need to have getters and setters).

    You could create Address as an abstract class, with a Copy(Address add) method.

    Alternatively, you could make Home and Work to HAVE an IAddress, and not extend one. The copy would then be immediate.

    0 讨论(0)
  • 2021-02-07 08:59

    You would need to create a method to do this

    public void CopyFrom(IAddress source)
    {
        this.Address1 = source.Address1;
        this.Address2 = source.Address2;
        this.City = source.city;
    }
    
    0 讨论(0)
  • 2021-02-07 09:02

    If you encapsulate the common parts of the home and work address into a separate class it may make your life easier. Then you can simply copy across that property. This seems like better design to me.

    Alternatively, you may be able to hack together a solution with reflection and attributes where the value of the properties in one object are copied over to the matching (and marked) properties in the other. Of course this is not going to be a one-line solution either but it may be faster and more maintainable than others if you have a large set of properties.

    0 讨论(0)
  • 2021-02-07 09:03

    Jimmy Bogard's AutoMapper is very useful for that kind of mapping operation.

    0 讨论(0)
  • 2021-02-07 09:04

    You could build an extension method:

    public static void CopyAddress(this IAddress source, IAddress destination)
    {
        if (source is null) throw new ArgumentNullException("source");
        if (destination is null) throw new ArgumentNullException("destination");
    
        //copy members:
        destination.Address1 = source.Address1;
        //...
    }
    
    0 讨论(0)
提交回复
热议问题