【发布时间】:2008-11-24 17:00:49
【问题描述】:
在用 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;
}
}
【问题讨论】:
标签: c# .net exception attributes