(请见下面我使用我接受的答案创建的解决方案)
我试图改善一些涉及反射的代码的可维护性。该应用程序具有一个.NET Remoting接口,公开了一个名为Execute
的方法,用于访问未包含在其已发布的远程接口中的应用程序部分。
以下是应用程序如何指定属性(此示例中为静态属性),以便可以通过Execute访问:
RemoteMgr.ExposeProperty("SomeSecret", typeof(SomeClass), "SomeProperty");
因此,远程用户可以调用:
string response = remoteObject.Execute("SomeSecret");
这个应用程序将使用反射来查找SomeClass.SomeProperty并将其作为字符串返回。
不幸的是,如果有人重命名了SomeProperty并忘记更改ExposeProperty()的第三个参数,它会破坏这个机制。
我需要相当于:
SomeClass.SomeProperty.GetTheNameOfThisPropertyAsAString()
有没有办法在ExposeProperty
的第三个参数中使用,这样重构工具就可以处理重命名了。
好的,这是我最终创建的代码(基于我选择的答案和他引用的问题):
// <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)
{
throw new ArgumentException("You must pass a lambda of the form: '() => Class.Property' or '() => object.Property'");
}
return me.Member.Name;
}
用法:
// Static Property
string name = GetPropertyName(() => SomeClass.SomeProperty);
// Instance Property
string name = GetPropertyName(() => someObject.SomeProperty);
现在有了这个很酷的功能,是时候简化ExposeProperty方法了。打磨门把手是危险的工作...