(请参阅下面我使用我接受的答案创建的解决方案)
我正在尝试提高一些涉及反射的代码的可维护性。该应用程序有一个 .NET Remoting 接口(interface)(除其他外)公开了一个名为 Execute
的方法,用于访问未包含在其发布的远程接口(interface)中的应用程序部分。
以下是应用程序如何指定可通过 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 方法了。抛光门 Handlebars 是一项危险的工作......
最佳答案
使用 C# 6.0,现在这不是问题,您可以这样做:
nameof(SomeProperty)
此表达式在编译时解析为 "SomeProperty"
。
关于c# - 以字符串形式获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2820660/