在用 C# 编写自定义属性时,我想知道是否有任何关于属性异常的指南或最佳实践。 属性是否应该检查给定参数的有效性?或者这是属性(property)使用者的任务?
在一个简单的测试中,我没有抛出异常,直到我在具有异常抛出属性的类型上使用 GetCustomAttributes。 我只是认为仅在明确要求时才从属性中获取异常有点尴尬。
异常(exception)的示例属性:
[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 中的自定义属性和异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/314779/