2012-05-09 24 views
2

是否有可能在程序集中扫描具有特定属性的方法?我目前正在开发Visual C++项目,但即使C#也适合我。我需要找到当前具有特殊属性Eg的所有方法。 [XYZ]适用于它。有什么想法吗?是否有可能在程序集中扫描具有特定属性的方法?

+0

您正在寻找C++/CLI代码来扫描.Net程序集以查找属性,对吗? – user7116

+0

@sixlettervariables:是的。 – Jaggu

回答

3

我已经使用Microsoft Roslyn进行类似的任务。它应该很容易。

让我知道你是否需要任何示例代码。

,并看看这个帖子太:http://blog.filipekberg.se/2011/10/20/using-roslyn-to-parse-c-code-files/

反射也可用于的是,GetCustomAttributes方法的返回给定成员上定义的所有属性...

好吧,试试这个:

this.GetType().GetMethods() 

环槽的所有方法和GetCustomAttributes

这应该是它。不幸的是我没有在我妻子的笔记本电脑上安装Visual Studio :)

+0

嗨动物,是的请。只是一些示例代码将非常感激。我没有使用Roslyn。我想使用反射。 – Jaggu

4

试试这个。它将搜索任何对象特定属性

 MemberInfo[] members = obj.GetType().GetMethods(); 
     foreach (MemberInfo m in members) 
     { 
      if (m.MemberType == MemberTypes.Method) 
      { 
       MethodInfo p = m as MethodInfo; 
       object[] attribs = p.GetCustomAttributes(false); 
       foreach (object attr in attribs) 
       { 
        XYZ v = attr as XYZ; 
        if (v != null) 
         DoSomething(); 
       } 
      } 
     } 
2

使用反射来获取的方法和抢属性

3

考虑到装配的路径:

static void FindAttributes(String^ assemblyPath) 
{ 
    Assembly^ assembly = Assembly::ReflectionOnlyLoadFrom(assemblyPath); 

    for each (Type^ typ in assembly->GetTypes()) 
    { 
     for each (CustomAttributeData^ attr 
      in CustomAttributeData::GetCustomAttributes(typ)) 
     { 
      Console::WriteLine("{0}: {1}", typ, attr); 
     } 
    } 
} 

请记住,这将加载您在应用程序域中使用的每个程序集,因此每次都可以在自己的AppDomain中调用此代码。

相关问题