【发布时间】:2012-03-28 20:02:25
【问题描述】:
我很难以谷歌查询的形式总结我的问题(也许我的 foo 已关闭):
我试图通过不编辑类型定义本身,而是通过使用接口修饰对象来为接口或类提供一些功能。我正在尝试的简单示例是附加一个名为 [Notify] 的属性,该属性定义了一个属性更改事件,理想情况下,为该事件的接口/类提供使用。我没有成功,所以我向任何可能的设备(如果有的话)开放以实现等效:
[Notify]
public interface IPerson
{
string Name { get; set; }
}
[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public class Notify: Attribute
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
使用 IPerson:
IPerson person = PersonFactory.create();
person.PropertyChanged += SomeDelegateHere // the center peice
当然,如果您复制了此代码,则人不会有 PropertyChanged。无论有没有属性,有没有一种方法可以在不更改定义的情况下为 IPerson 提供更多功能(即不添加接口或基类)。我知道属性也在发生变化,但我对元数据方法很满意。
提前感谢您提供的任何启示。
【问题讨论】:
标签: c# attributes custom-attributes