简体   繁体   English

C#自定义属性可以指定应用于它的方法的类型吗?

[英]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 . 如果该方法具有MyAttribute1MyAttribute2MyAttribute3 ,则检查该方法的代码可以执行操作。

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.

相关问题 在C#中,属性可以应用于静态类,方法还是属性? - In C#, can an attribute be applied to a static class, method or property? C# 停止自定义属性应用于类 - C# stop custom attribute from being applied to class 断言将属性应用于c#中的方法的最短方法是什么? - Whats the shortest way to assert that an attribute is applied to method in c#? 在C#中,如何检查属性上是否应用了XmlIgnore属性? - In C# how can I check that XmlIgnore attribute is applied on a property or not? C#运算符'/'不能应用于'方法组'和'int类型的操作数 - C# Operator '/' cannot be applied to operands of type 'method group' and 'int C# 获取自定义属性扩展方法 - C# get custom attribute extension method C#自定义属性Targets.Method WHERE returntype = type && IsStatic - C# Custom Attribute, Targets.Method WHERE returntype = type && IsStatic 如何在LINQ查询中指定自定义方法(C#Entity Framework) - How to specify a custom method in a LINQ query (C# Entity Framework) 如何在c#中指定通用列表类型扩展方法的参数 - How to specify parameter for generic list type extension method in c# 有没有办法在C#方法签名中指定“当前类的类型”? - Is there a way to specify “type of current class” in a C# method signature?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM