[英]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? 我知道我可以使用
[AttributeUsage(AttributeTargets.Method)]
来确保只能将自定义属性应用于方法,但是如果将自定义属性应用于具有以下属性的方法,我可以走得更远并出现编译时错误:我指定的签名以外的签名?
For example, can I create an attribute that can only be attached to a method that returns int
and takes a single int
parameter? 例如,是否可以创建只能附加到返回
int
并接受单个int
参数的方法的属性?
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. 您不能这样做,但是有一种解决方法:.NET Framework支持方法的输入参数和返回值的属性。
[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
. 如果该方法具有
MyAttribute1
, MyAttribute2
和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. 您可以在编译期间使用PostSharp应用属性。 This link demonstrates Automatically Adding DataContract and DataMember Attributes
此链接演示了自动添加DataContract和DataMember属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.