谈到物业本身在C#。反射?通用?类型? [英] Referring to the property itself in C#. Reflection? Generic? Type?

查看:116
本文介绍了谈到物业本身在C#。反射?通用?类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请容忍我,如果这个问题没有得到很好的制定。不知道是问题的一部分。

Please bear with me if this question isn't well formulated. Not knowing is part of the problem.

的想什么,我要完成的一个例子可以在WPF PropertyChangedEventArgs找到。如果你想要一个属性在WPF改变标志,像这样做:

An example of what I'd like to accomplish can be found in PropertyChangedEventArgs in WPF. If you want to flag that a property has changed in WPF, you do it like this:

PropertyChanged(this, new PropertyChangedEventArgs("propertyName"));

您传递一个字符串以PropertyChangedEventArgs引用在属性名称变了。

You pass a string to PropertyChangedEventArgs that refers to the property name that changed.

您可以想像,我真的不想要的属性名称硬编码的字符串都在我的代码。重构 - 重命名怀念它,当然,这使得它不仅美观而且吸引力容易出错也是如此。

You can imagine that I don't really want hard coded strings for property names all over my code. Refactor-rename misses it, of course, which makes it not only aesthetically unappealing but error prone as well.

我宁愿指房产本身 ...不知何故。

I'd much rather refer to the property itself ... somehow.

PropertyChanged(this, new PropertyChangedEventArgs(?SomeClass.PropertyName?));



好像我应该可以,让我说类似的短暂方法来包装这个以上。

It seems like I should be able to wrap this in a short method that lets me say something like the above.

private void MyPropertyChanged(??) {
  PropertyChanged(this, new PropertyChangedEventArgs(??.ToString()??));
}

... so I can say something like:
MyPropertyChanged(Person.Name); //where I'm interested in the property *itself*



到目前为止,我画一个空白

So far I'm drawing a blank.

推荐答案

有没有做到这一点直接的方式,可惜的是,但是,您可以通过表达式做它在.NET 3.5。 看到这里了解。要复制的例子:

There isn't a direct way to do this, unfortunately; however, you can do it in .NET 3.5 via Expression. See here for more. To copy the example:

PropertyInfo prop = PropertyHelper<Foo>.GetProperty(x => x.Bar);



(这是很简单的更改返回名称,而不是的PropertyInfo

同样,这将是非常简单的写一个变体。

Likewise, it would be pretty simple to write a variant:

OnPropertyChanged(x=>x.Name);



使用:

using:

OnPropertyChanged<T>(Expression<Func<MyType,T>> property) {...}

这篇关于谈到物业本身在C#。反射?通用?类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆