开发者

Custom Attribute - Set Attribute Usage for Only Private Members

I creating a custom attribute and I would like to the set the AttributeUsage (or maybe some other att开发者_开发知识库ribute in the attribute class) so that I my attribute can only be used in private methods, is that possible?

Thanks in advance for the answers!


There is no such feature available in C# (as of 4.0) that allows you to restrict attribute usage based on a member's accessibility.

The question would be why do you want to do that?

Because given below attribute,

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
sealed class MethodTestAttribute : Attribute
{
    public MethodTestAttribute()
    { }
}

and below class,

public class MyClass
{
    [MethodTest]
    private void PrivateMethod()
    { }

    [MethodTest]
    protected void ProtectedMethod()
    { }

    [MethodTest]
    public void PublicMethod()
    { }
}

You can easily get attributes of private methods using following code:

var attributes = typeof(MyClass).GetMethods().
                 Where(m => m.IsPrivate).
                 SelectMany(m => m.GetCustomAttributes(typeof(MethodTestAttribute), false));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜