2009-08-28 59 views
8

我在这里创建了一个名为AAtribute的自定义属性,例如一个名为B的类,其中一个或多个方法使用该属性。是否可以将保存属性的方法的MethodInfo(在这种情况下是BMethod1)作为属性中的一个,而不必遍历整个程序集并查看所有已定义的方法的属性?并且它们是其他AttributeTargets(参数/类型/属性/ ...)的模拟方式吗?我不想要一个使用该类型的Attribute的所有方法的数组,但只需要具有此Attirbute对象的方法。我想用它来为方法添加额外的约束(返回类型,参数,名称,其他Attribute-usage,...)。快速访问C#中保存属性的类型/方法/ ...

[AttributeUsage(AttributeTargets.Method)] 
public class AAtribute : Attribute { 

    //some fields and properties 

    public AAtribute() {//perhaps with some parameters 
     //some operations 
     MethodInfo mi;//acces to the MethodInfo with this Attribute 
         //as an Attribute (the question) 
     //some operations with the MethodInfo 
    } 

    //some methods 

} 

public class B { 

    //some fields, properties and constructors 

    [A] 
    public void BMethod1() { 
     //some operations 
    } 

    //other methods 

} 
+0

好问题,我也想知道答案... – 2009-08-28 10:06:41

回答

2

如果我正确理解了你的问题,你想在属性代码内获得这个属性应用到的对象(在这种情况下是一个方法)。
我很确定没有直接的方法来做到这一点 - 属性不知道它所连接的对象,这种关联是相反的。

最好的,我可以建议你是像下面这样的解决方法:

using System; 
using System.Reflection; 

namespace test { 

    [AttributeUsage(AttributeTargets.Method)] 
    public class AAttribute : Attribute { 
     public AAttribute(Type type,string method) { 
      MethodInfo mi = type.GetMethod(method); 
     } 
    } 

    public class B { 
     [A(typeof(B),"BMethod1")] 
     public void BMethod1() { 
     } 
    } 
} 

注意
你想通过访问属性的构造函数中的MethodInfo实现什么?也许有另一种方式来获得你的目标......

编辑

作为另一种可能的解决方案,您可能会提供您的属性,做检查的静态方法 - 但这需要遍历MethodInfos。

using System; 
using System.Reflection; 
namespace test { 

    [AttributeUsage(AttributeTargets.Method)] 
    public class AAttribute : Attribute { 
     public static void CheckType<T>() { 
      foreach (MethodInfo mi in typeof(T).GetMethods()) { 
       AAttribute[] attributes = (AAttribute[])mi.GetCustomAttributes(typeof(AAttribute), false); 
       if (0 != attributes.Length) { 
        // do your checks here 
       } 
      } 
     } 
    } 

    public class B { 
     [A] 
     public void BMethod1() { 
     } 
     [A] 
     public int BMethod2() { 
      return 0; 
     } 
    } 

    public static class Program { 
     public static void Main() { 
      AAttribute.CheckType<B>(); 
     } 
    } 
} 
+0

就像我已经说过的,我想在它上面添加additiol约束(返回类型,参数数量,参数类型,方法名称...)。如果该方法无效,则可抛出异常。但无论原因是什么,如果你可以访问属性链接的东西,这不是逻辑吗? – 2009-08-28 11:59:52

+0

是的,但是你想对这些限制做什么?无论如何,只有在尝试反映类型时,该属性才会被实例化。 – 2009-08-28 12:41:31

0

要了解某个方法是否应用了某个属性,您已经拥有MethodInfo。

var type = obj.GetType(); 
foreach(var method in type.GetMethods()) 
{ 
    var attributes = method.GetCustomAttributes(typeof(AAtribute)); 
    if(attributes.Length > 0) 
    { 
     //this method has AAtribute applied at least once 
    } 
}

+0

是的,但是你怎么从属性内部做到这一点?有没有办法知道属性的当前实例应用于哪个方法(或成员)? – 2009-08-28 10:07:41

2

我认为答案是否定的。或者至少不是以合理的方式。只有通过MethodInfo查找属性后,才会构造该属性的实例。实例化具有该属性的方法的类将不会实例化该属性。属性实例只有在您开始通过反射来查找它们时才会创建。