简体   繁体   English

使用属性在.NET中引发异常

[英]Using an attribute to throw an exception in .NET

Is it possible to use some kind of attribute to throw an exception. 是否可以使用某种属性引发异常。 This is what I mean. 这就是我的意思。 Instead of doing this: 而不是这样做:

public int Age
{
    get
    {
        return this.age;
    }

    set
    {
        this.age = value;
        NotifyPropertyChanged("Age");

        if (value < 18)
        {
            throw new Exception("age < 18");
        }

    }
}

Do something like this: 做这样的事情:

[Range(18,100, ErrorMessage="Must be older than 18")]
public int Age
{
    get
    {
        return this.age;
    }

    set
    {
        this.age = value;
        NotifyPropertyChanged("Age");
    }
}

Any help would be greatly appreciated! 任何帮助将不胜感激!

Best Regards, Kiril 最好的问候,基里尔

You're looking for an AOP (Aspect Oriented Programming) library, which can do this quite easily. 您正在寻找一个AOP(面向方面​​的编程)库,可以很容易地做到这一点。 I would recommend giving PostSharp a try. 我建议尝试一下PostSharp The example on the home page should give an indication how you might use it on a property/method. 主页上的示例应说明如何在属性/方法上使用它。

No, that's not possible. 不,那不可能。 You will have to do the validation yourself in the setter - just like NotifyPropertyChanged. 您将需要在setter中自己进行验证-就像NotifyPropertyChanged一样。

Btw - this is called "Aspect Oriented Programming". 顺便说一句-这被称为“面向方面的编程”。

As the accepted solution says, it's impossible to do this directly but can be achived by using a tool like PostSharp. 正如公认的解决方案所说,不可能直接做到这一点,但是可以通过使用PostSharp之类的工具来实现。 Just to add to what's already been told, I wouldn't recommend throwing from a property, or doing validation of this sort on assignment as generally it doesn't hold too much value and can be the cause of some trouble. 只是为了增加已被告知的内容,我不建议从属性中抛出异常,也不建议对赋值进行此类验证,因为通常它并没有太多价值,并且可能会引起一些麻烦。 It may depend on the scenario though. 但是,这可能取决于场景。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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