简体   繁体   中英

Using an Attribute to raise an event

I have some code I would like to simplify. Here is the code:

private int id;
public int Id
{
    get { return id; }
    set
    {
        id = value;
        base.OnPropertyChanged("Id");
    }
}

I was thinking using an Attribute to only get:

[RaiseOnPropertyChanged()]
public int Id { get; set; }

How can that be done? Or can it be done using an attribute?

Alas, you can't do that within the confines of C# itself; you'll need to manipulate things at the IL level to get what you want. However, you can use aspect-oriented techniques like that provided by PostSharp to get the desired result.

The best option for you to explore is Aspect-Oriented-Programming using a framework such as PostSharp.

PostSharp will let you define attributes that will be 'fleshed-out' with code templates during compile time. Their site has several examples and their upcoming major release will significantly ease working with the tool for exactly these types of scenarios.

您可以使用PostSharp动态地实现INotifyPropertyChanged接口。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM