Is there a good strongly typed way to do PropertyChanged events in C#?

前端 未结 7 1131
轮回少年
轮回少年 2020-12-05 12:19

It must be a somewhat common event to change the name of a property and expect the Rename functionality in Visual Studio to take care of all the necessary renaming, except f

7条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-05 12:36

    In theory, you could use MethodBase.GetCurrentMethod().Name.Substring(4) from within the property setter. Unfortunately, Google search reveals that it seems to have a significant performance impact. Two more things to consider:

    • JIT inlining can impact this in unexpected ways. (stackoverflow.com/questions/616779/can-i-check-if-the-c-compiler-inlined-a-method-call)
    • In theory, the IL call to MethodBase.GetCurrentMethod() could be trivially replaced by the JIT at runtime with a ldtoken instruction followed by a call to MethodBase.GetMethodFromHandle(), which would be very fast. I guess users just haven't expressed a need for this. (msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.ldtoken.aspx)
    • Completely my opinion here, but I think it'd be nice to have fieldof() and methodof() operators in C#. I believe it would greatly improve the reliability of the code analysis/refactoring tools in projects that require that ability.

提交回复
热议问题