[英]How can I get the name and value of a property using reflection?
I have this code and I am using it to raise the PropertyChanged event without passing the name of property to the function. 我有这个代码,我用它来引发PropertyChanged事件而不将属性名称传递给函数。
private void RaisePropertyChanged<TValue>(Expression<Func<TValue>> propertySelector)
{
var memberExpression = propertySelector.Body as MemberExpression;
if (memberExpression != null)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(memberExpression.Member.Name));
}
}
}
and I am calling it in this way: 而我这样称呼它:
this.RaisePropertyChanged(() => this.IsReady);
Which will raise the PropertyChanged event for the IsReady property. 这将引发IsReady属性的PropertyChanged事件。 I like the idea as writing code in this way will help to change the name of the property very easily.
我喜欢这个想法,因为以这种方式编写代码将有助于非常容易地更改属性的名称。
Now I want to use the same technique to pass the name and value of a property to a method. 现在我想使用相同的技术将属性的名称和值传递给方法。 Is there any way that I can do this?
有什么方法可以做到这一点吗?
You already have it: 你已经拥有它:
string name = memberExpression.Member.Name;
TValue value = propertySelector.Compile()();
An alternative would be to look at the member.MemberType
, cast to PropertyInfo
or FieldInfo
respectively: 另一种方法是查看
member.MemberType
,分别转换为PropertyInfo
或FieldInfo
:
var member = memberExpression.Member;
string name = member.Name;
object value;
switch(member.MemberType) {
case MemberTypes.Field:
value = ((FieldInfo)member).GetValue(this);
break;
case MemberTypes.Property:
value = ((PropertyInfo)member).GetValue(this, null);
break;
default:
throw new NotSupportedException(member.MemberType.ToString());
}
However, a simpler approach is... to simply pass the name and value to the method: 但是, 更简单的方法是......简单地将名称和值传递给方法:
Foo("IsReady", IsReady);
It depends a bit on how efficient it needs to be, though (reflection/expression does add an overhead - whether that is significant depends on the context). 它取决于它需要多高的效率,但是(反射/表达确实增加了开销 - 这是否重要取决于上下文)。
要获取名称,您可以使用memberExpression.Member.Name
并获取值,您可以使用this.GetType().GetProperty (memberExpression.Member.Name).GetGetMethod().Invoke (this, null)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.