开发者

How to pass Exceptions array to Attribute

开发者 https://www.devze.com 2023-03-25 01:24 出处:网络
I am creating Attribute where I need to pass array of Exceptions, how to do that? Let\'s say [assembly: MyAttribute(ExceptionList = [System.Web.HttpException, System.Threading.Threa开发者_JAVA百科d

I am creating Attribute where I need to pass array of Exceptions, how to do that?

Let's say

[assembly: MyAttribute(ExceptionList = [System.Web.HttpException, System.Threading.Threa开发者_JAVA百科dAbortException]); 


If you want to pass exception types then you can use typeof:

[assembly: MyAttribute(ExceptionList = [typeof(System.Web.HttpException), typeof(System.Threading.ThreadAbortException])); 

If you want to pass exception objects, it is not possible. Arguments to attribute constructors can only be constant values (or expressions of a couple of types for which a special exception is made).


You need to pass a list of types rather than Exceptions. This should get you started

[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
sealed class MyAttribute : Attribute {
    public MyAttribute(Type[] exceptionList) {
    }
}

[MyAttribute(new Type[] { typeof(ArgumentException), typeof(OtherException) } )]
class Test {
    ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消