jleach
jleach

Reputation: 7800

C# copy generic object by val

I'm making a generic control subclass that handles change tracking (and other things) for use primarily when the data is bound to an underlying object (ultimately a database, but I shouldn't count on this).

I need to track the value at the start of editing, the current value at any given point, and at any given point maintain a clean separation of those. Because I don't know the type, the applicable properties are declared as objects:

    class DataboundControl : Control
    {

        private string _valuePropertyName;
        private string _changedEventName;

        public Control BaseControl { get; private set; }
        public object Value { get { return Objects.GetPropertyValue(this.BaseControl, _valuePropertyName); } }
        public bool IsDirty { get { return object.Equals(this.Value, this.ControlEditStartValue); } }

        // change tracking
        public object ControlEditStartValue { get; set; }
        public object RecordEditStartValue { get; set; }



        public DataboundControl(Control control, string valuePropertyName, string changedEventName) {

            this.BaseControl = control;

            this._valuePropertyName = valuePropertyName;
            this._changedEventName = changedEventName;

            registerChangedEvent();
        }
}

In the above example, I need to store "non-reffed" copies of ControlEditStartValue and RecordEditStartValue.

Given that the control values will almost always be of a standard value-ish type (string, int, bool - something that maps to a database field), I'd prefer to treat it like that by default and handle exception cases explicitly.

I feel like this should be very easy, yet there's a whole mess of shallow/deep copy stuff that goes along with it. Given that the values will nearly always be very "shallow" in terms of an object, what would be the best way to go about this?

Upvotes: 0

Views: 149

Answers (1)

feiyun0112
feiyun0112

Reputation: 771

use Json.Net Serialize/Deserialize the values

Upvotes: 1

Related Questions