4

我创建了一个自定义属性,我想设置AttributeUsage(或者可能是属性类中的其他属性),这样我的属性只能在私有方法中使用,这可能吗?

提前感谢您的回答!

4

1 回答 1

3

没有这样的功能可以C# (as of 4.0)让您attribute根据成员的可访问性来限制使用。

问题是你为什么要这样做?

因为给出了以下属性,

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

及以下,

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

    [MethodTest]
    protected void ProtectedMethod()
    { }

    [MethodTest]
    public void PublicMethod()
    { }
}

您可以使用以下代码轻松获取私有方法的属性:

var attributes = typeof(MyClass).GetMethods().
                 Where(m => m.IsPrivate).
                 SelectMany(m => m.GetCustomAttributes(typeof(MethodTestAttribute), false));
于 2010-12-21T16:30:48.640 回答