Reputation: 925
So, I have a custom attribute that looks like this:
[AttributeUsage(System.AttributeTargets.Method, AllowMultiple = false)]
public class MyAttribute: System.Attribute
{
private string name;
public double version;
public MyAttribute(string _name)
{
this.name = _name;
version = 1.0;
}
}
Is it possible to add the following conditions to this attribute:
Method.ReturnType = typeof(specificClass)
Method.IsStatic
Also, how do I implement the following condition?
public static void Do(Func<type> func) where func : MyAttribute //make sure Func<type> is decorated with my attribute
{
//do something with 'func'
}
Upvotes: 0
Views: 707
Reputation: 8892
No, it is not. AttributeUsage
determines how a custom attribute class can be used.
The first AttributeUsage
argument (ValidOn
) must be one or more elements of the AttributeTargets
enumeration. Multiple target types can be linked together with the OR operator, like this:
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
class NewPropertyOrFieldAttribute : Attribute { }
If the AllowMultiple
argument is set to true, then the resulting attribute can be applied more than once to a single entity, like this:
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
class MultiUseAttr : Attribute { }
[MultiUseAttr]
[MultiUseAttr]
class Class1 { }
[MultiUseAttr, MultiUseAttr]
class Class2 { }
If Inherited
is set to false, then the attribute is not inherited by classes that are derived from a class that is attributed. For example:
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
class Attr1 : Attribute { }
[Attr1]
class BClass { }
// In this case Attr1 is not applied to DClass via inheritance.
class DClass : BClass { }
That is all parameters that you can control for attribute usage in compile time. You can validate usage scenarios in the run-time via reflection but it's slow and error-prone way.
Upvotes: 1