Cruft code. IoC to the rescue

后端 未结 4 1459
我在风中等你
我在风中等你 2021-01-30 23:08

In question about usefulness of IoC Container, the winning submitter mentioned that with an IoC container you can take this:

public class UglyCustomer : INotifyP         


        
4条回答
  •  -上瘾入骨i
    2021-01-30 23:56

    For your second code snippet to work, NotifyPropertyChangedWrapper would certainly have to use reflection (or dynamic) to generate a class that provides an interface compatible with Customer and implements the automatic property notification. There shouldn't be any data binding issues, but there would be a little overhead.

    An simplified implementation that uses a dynamic object could look something like this:

    public class NotifyPropertyChangedWrapper 
        : DynamicObject, INotifyPropertyChanged
    {
        private T _obj;
    
        public NotifyPropertyChangedWrapper(T obj)
        {
            _obj = obj;
        }
    
        public override bool TryGetMember(
            GetMemberBinder binder, out object result)
        {
            result = typeof(T).GetProperty(binder.Name).GetValue(_obj);
            return true;
        }
    
        // If you try to set a value of a property that is
        // not defined in the class, this method is called.
        public override bool TrySetMember(
            SetMemberBinder binder, object value)
        {
            typeof(T).GetProperty(binder.Name).SetValue(_obj, value);
            OnPropertyChanged(binder.Name);
            return true;
        }
    
        // Implement OnPropertyChanged...
    }
    

    Obviously, any code that consumes one of these objects would lose any static type safety. The other option is to generate a class implementing the same interface as the class being wrapped. There are lots of examples for this on the web. The main requirement is that your Customer would have to either be an interface or it would need all of its properties to be virtual.

提交回复
热议问题