(参见下面我使用我接受的答案创建的解决方案)
我正在尝试提高一些涉及反射的代码的可维护性.该应用程序有一个.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) 能够在没有明确指定已更改属性的名称的情况下引发"PropertyChanged"事件是一件好事.我想做这样的事情:
public string MyString
{
get { return _myString; }
set
{
ChangePropertyAndNotify<string>(val=>_myString=val, value);
}
}
private void ChangePropertyAndNotify<T>(Action<T> setter, T value)
{
setter(value);
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(setter.Method.Name));
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,收到的名称是lambda方法的名称:"<set_MyString> b__0".
谢谢.
我有一个问题,一直困扰我一段时间,我找不到答案.
我需要获取Lambda表达式中引用的属性的名称.我会将lambda表达式提供给一个返回字符串的方法.例如,如果我有:
x => x.WeirdPropertyName
Run Code Online (Sandbox Code Playgroud)
然后该方法将返回:
"WeirdPropertyName"
Run Code Online (Sandbox Code Playgroud)
我已经读过它可以用表达式树来完成,但答案已经没有了.
谢谢你的帮助
我有一个房产Myclass:
public class MyClass{
public string FirstName {get;set;}
}
Run Code Online (Sandbox Code Playgroud)
如何在没有字符串的情况下获得PropertyInfo(使用GetProperty("FirstName"))?
今天我用这个:
PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty("FirstName");
Run Code Online (Sandbox Code Playgroud)
有没有这样的使用方法:
PropertyInfo propertyTitleNews = typeof(MyClass).GetProperty(MyClass.FirstName);
Run Code Online (Sandbox Code Playgroud)
?