CallerMemberName如何工作? [英] How CallerMemberName works?
问题描述
我见过一些使用[CallerMemberName]作为方法参数前缀的INotifyPropertyChanged成员方法。我想知道它是如何工作的。怎么做一些类似的呢?请问任何人解释一下吗?
注:
我已经读过一些链接 [ ^ ]我们可以在其中找到一些额外的改进。 net4.5关于属性使用。请告诉我一些与此类似的链接:)
我的自定义属性类
Hi,
i have seen some of the INotifyPropertyChanged member method using [CallerMemberName] as a method argument prefix. i want to know how actually it works. how to do some this similar to it? can any one explain me please?
Note:
I have already read some of the links [^]where we can find some additional improvements in .net4.5 regarding attribute usage. please let me know some links other than similar to this :)
My Custom attribute class
namespace AttributeTesting
{
[AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
public class CallerMember : Attribute
{
public string ParameterName { get; set; }
}
}
已实施employeeClass
Implemented employeeClass
namespace AttributeTesting.Data
{
[CallerMember]
public class EmployeeData : INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; OnPropertyChanged(); }
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMember] string ParameterName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(ParameterName));
}
}
#endregion
}
}
尝试使其工作
try to make it work
namespace AttributeTesting
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += OnMainWindowLoaded;
}
void OnMainWindowLoaded(object sender, RoutedEventArgs e)
{
EmployeeData EmployeeData = new EmployeeData { Name = "GoldCoin" };
}
}
}
无法实现我的自定义属性。我该怎么做呢
注意:
我正在尝试实现.net 4.5具有的功能。我在.net 4.0中开发的解决方案中的相同:)
Unable to implement my custom attribute. what should i do next
Note:
I am trying to implement something that .net 4.5 has. The same in my solution which was developed in .net 4.0 :)
推荐答案
这称为属性。
这是MSDN页面关于CallerMemberNameAttribute:
CallerMemberNameAttribute [ ^ ]
您可以通过派生自属性类 [ ^ ]。
类名必须以属性字为后缀,但在使用时不会显示在你的代码中。
示例:
That is called an attribute.
Here is the MSDN page about the CallerMemberNameAttribute:
CallerMemberNameAttribute[^]
You can define your own attribute by deriving from Attribute Class[^].
The class name must be suffixed with 'Attribute' word, but this does not appear when you use it in your code.
Example:
public class MyOwnAttrAttribute : Attribute
{
// ...
}
[MyOwnAttr]
public class MyDecoratedClass
{
// ...
}
尝试将实现更改为:
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
这篇关于CallerMemberName如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!