简体   繁体   中英

How to override a property setter using custom attribute?

ex.

[NoZero()]
public int Quantity{ get; set; }

Basically, I don't want the Quantity to be set to less than zero.

This doesn't answer your question directly, but to offer an interesting alternative.

If you are making use of an IoC framework and one which has the possibilities of "interception" you could force your property access to be intercepted (as long as the class is passed in via IoC off course).

Ninject Intercept any method with certain attribute?

I haven't tried it myself with property access, but in theory it could work.

Or alternatively, using a code-weaving library directly: https://github.com/Fody/Fody this effectively weaves itself into the IL.

The traditional way to do this is

protected int _quantity;

public int Quantity
{
    set
    {
        if (_quantity < 0) throw new ArgumentOutOfRangeException("Some message");
        _quantity = value;
    }
    get
    {
        return _quantity;
    }
}

You can't really do it with attributes unless you write code that checks for the attributes before setting the property. This is how DataAnnotation attributes work, for example. In the document, notice the following:

To implement the above requirement we need to code in the UI layer to accommodate/validate the above criteria's.

So you see, you'd have to write a lot of complicated code, and be careful not to set the property directly. That is why most people don't do it with attributes.

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