简体   繁体   中英

Can a C# custom attribute specify the type of method it is applied to?

I know I can use [AttributeUsage(AttributeTargets.Method)] to make sure a custom attribute can only be applied to a method, but can I go further and get a compile-time error if the custom attribute is applied to a method with a signature other than the one I specify?

For example, can I create an attribute that can only be attached to a method that returns int and takes a single int parameter?

but can I go further and get a compile-time error if the custom attribute is applied to a method with a signature other than the one I specify?

No, you can't, this simply is not supported.

You can't do that, but you've a workaround: .NET Framework supports attributes on methods' input parameters and return values.

[MyAttribute1]
[return: MyAttribute2]
public int Method([MyAttribute3] int some)
{
    return "";
}

And the code inspecting the method can do things if the method has MyAttribute1 , MyAttribute2 and MyAttribute3 .

Depending on your needs, maybe this is too ugly, but I don't know your actual requirements!

You can apply an attribute during compilation using PostSharp. This link demonstrates Automatically Adding DataContract and DataMember Attributes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM