.net中的自定义属性和例外

Fio*_*onn 9 .net c# attributes exception

在C#中编写自定义属性时,我想知道是否有关于属性中的异常的指南或最佳实践.属性应该检查给定参数的有效性吗?或者这是属性用户的任务?

在一个简单的测试中,我做了异常,直到我在具有异常抛出属性的类型上使用GetCustomAttributes时才抛出异常.我只是认为仅在明确要求它时才从属性中获取异常有点尴尬.


示例属性有异常:

[AttributeUsage(AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
sealed public class MyAttribute : Attribute
{
    public string SomeValue { get; private set; }

    public MyAttribute(string someValue)
    {
        if(string.IsNullOrEmpty(someValue))
        {
            throw new ArgumentNullException("path");
        }

        if(!someOtherCheck(someValue))
        {
            throw MyAttributeException("An other error occured");
        }

        SomeValue = someValue;
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 7

属性仅在您使用反射时实际构建,因此这是您唯一可以抛出异常的时间.我不记得曾经使用过属性并让它抛出异常.属性通常提供数据而不是真实的行为 - 我希望使用该属性的代码提供任何验证.我知道这不像普通的封装,但它是我的经验中的方式.