Best way to clone properties of disparate objects

后端 未结 1 1683
滥情空心
滥情空心 2020-12-02 02:09

I have an MVC3 application that needs to sync view models with database models. I found myself writing way too much code to copy properties back and forth between the differ

相关标签:
1条回答
  • 2020-12-02 03:01

    You may consider using Object.MemberwiseClone method.

    The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. (docs.microsoft)

    The method is protected. It means that you have to implement the Clone method in your classes. To make things even more fance you can add ICloneable to your classes as well.

    class MyClass: ICloneable
    {
        // all your code
        MyClass Clone()
        {
            return (MyClass)this.MemberwiseClone();
        }
    }
    
    0 讨论(0)
提交回复
热议问题