(参见下面我使用我接受的答案创建的解决方案)
我正在尝试提高一些涉及反射的代码的可维护性.该应用程序有一个.NET Remoting接口,公开(除此之外)一个名为Execute的方法,用于访问未包含在其已发布的远程接口中的应用程序部分.
以下是应用程序如何指定可通过Execute访问的属性(本例中为静态属性):
RemoteMgr.ExposeProperty("SomeSecret", typeof(SomeClass), "SomeProperty");
Run Code Online (Sandbox Code Playgroud)
所以远程用户可以调用:
string response = remoteObject.Execute("SomeSecret");
Run Code Online (Sandbox Code Playgroud)
并且应用程序将使用反射来查找SomeClass.SomeProperty并将其值作为字符串返回.
不幸的是,如果有人重命名SomeProperty并忘记更改ExposeProperty()的第3个parm,它会破坏这种机制.
我需要相当于:
SomeClass.SomeProperty.GetTheNameOfThisPropertyAsAString()
Run Code Online (Sandbox Code Playgroud)
在ExposeProperty中用作第三个parm,因此重构工具将负责重命名.
有没有办法做到这一点?提前致谢.
好的,这是我最终创建的内容(根据我选择的答案和他引用的问题):
// <summary>
// Get the name of a static or instance property from a property access lambda.
// </summary>
// <typeparam name="T">Type of the property</typeparam>
// <param name="propertyLambda">lambda expression of the form: '() => Class.Property' or '() => object.Property'</param>
// <returns>The name of the property</returns>
public string GetPropertyName<T>(Expression<Func<T>> propertyLambda)
{
var me = propertyLambda.Body as MemberExpression;
if (me == null)
{ …Run Code Online (Sandbox Code Playgroud)