Which of these two is the proper way to wire up change-notification for the IPropertyChangedNotification interface?
someObj.PropertyChanged += new PropertyChangedEventHandler(SomeObjPropChanged);
someObj.PropertyChanged += SomeObjPropChanged;
Both of these seem to work, but I'm not really clear on the difference. Is one just a shortcut for the other, or can it by any chance have to do with memory management and unintentionally keeping things around? (I've read that there are issues with wiring up change notifications and event ha开发者_如何学Pythonndlers causing potential memory leaks thanks to objects unintentionally becoming rooted.)
So any takers?
M
I think you'll find they result in the same IL.
Update:
PropertyChanged += new PropertyChangedEventHandler(SomeEventHandler);
PropertyChanged += SomeEventHandler;
Results in IL using ildasm:
IL_0006: l4zyOP
IL_0007: nop
//000011: PropertyChanged += new PropertyChangedEventHandler(SomeEventHandler);
IL_0008: ldarg.0
IL_0009: ldarg.0
IL_000a: ldftn instance void StackOverflow_5535253.SomeClass::SomeEventHandler(object, class [System]System.ComponentModel.PropertyChangedEventArgs)
IL_0010: newobj instance void [System]System.ComponentModel.PropertyChangedEventHandler::.ctor(object, native int)
IL_0015: call instance void StackOverflow_5535253.SomeClass::add_PropertyChanged(class [System]System.ComponentModel.PropertyChangedEventHandler)
IL_001a: nop
//000012: PropertyChanged += SomeEventHandler;
IL_001b: ldarg.0
IL_001c: ldarg.0
IL_001d: ldftn instance void StackOverflow_5535253.SomeClass::SomeEventHandler(object, class [System]System.ComponentModel.PropertyChangedEventArgs)
IL_0023: newobj instance void [System]System.ComponentModel.PropertyChangedEventHandler::.ctor(object, native int)
IL_0028: call instance void StackOverflow_5535253.SomeClass::add_PropertyChanged(class [System]System.ComponentModel.PropertyChangedEventHandler)
IL_002d: nop
There is absolutely no difference.
someObj.PropertyChanged += SomeObjPropChanged
is just a shortcut which is expanded to someObj.PropertyChanged += new PropertyChangedEventHandler(SomeObjPropChanged)
by the C# compiler. I prefer the first way, because it looks clearer to me.
精彩评论