2010-12-21 30 views
4

我创建自定义属性,我想在设置AttributeUsage(或者在属性类的一些其他属性),所以我在我的属性只能用来设置属性用法在私人方法,这是可能的吗?自定义属性 - 只为私人会员

在此先感谢您的答案!

+1

我很感兴趣了解私有属性的原因。 – Amy 2010-12-21 18:31:19

回答

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));