在C#中編寫自定義屬性時,我想知道是否有任何有關屬性例外的指導方針或最佳做法。 該屬性應該檢查給定參數的有效性嗎?或者這是財產使用者的任務?自定義屬性和例外.net
在一個簡單的測試中,我沒有拋出異常,直到我對帶有異常拋出屬性的類型使用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;
}
}