是否可以扫描装配中具有特定属性的方法?我目前正在开发Visual C ++项目,但即使C#对我来说还不错。我需要找到当前具有特定属性Eg的所有方法。 [XYZ]
适用于此。有什么想法吗?
答案 0 :(得分: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();
}
}
}
答案 1 :(得分:3)
我使用Microsoft Roslyn进行类似的任务。这应该很容易。
如果您需要任何示例代码,请告诉我。
请看一下这篇文章:http://blog.filipekberg.se/2011/10/20/using-roslyn-to-parse-c-code-files/
也可以使用反射,GetCustomAttributes方法返回给定成员上定义的所有属性......
好的,试试这个:
this.GetType().GetMethods()
循环所有方法和GetCustomAttributes
那应该是它。不幸的是我没有在我妻子的笔记本电脑上安装Visual Studio:)
答案 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);
}
}
}
请记住,这会将您使用的每个程序集加载到Application Domain中,因此每次都可以在自己的AppDomain中调用此代码。
答案 3 :(得分:2)
使用Reflection获取方法并获取属性