查询程序集

Gha*_*han 2 reflection powershell unit-testing

我有一个.NET程序集,它有几十个类和方法,它们是单元测试方法.我想用一个标有属性Ignore的方法生成一个报告,你知道一个简单的方法吗?

Bob*_*Bob 6

您需要获取自定义属性方法

Assembly ass = Assembly.Load("yourassembly.dll");
object[] attributes = ass.GetCustomAttributes(typeof(IgnoreAttribute), false));
Run Code Online (Sandbox Code Playgroud)

此方法也存在于方法对象上,因此您可以遍历程序集中的所有类型并遍历其所有方法,并调用相同的方法.

foreach(Type type in ass.GetTypes()) {
    foreach(MethodInfo method in type.GetMethods()) {
       method.GetCustomAttributes(typeof(IgnoreAttribute), true));
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑,这里有一些关于powershell语法的帮助,虽然我必须说,我不是PowerShell流利的.我相信有人可以比我下面的垃圾做得更好.

$types = [System.Reflection.Assembly]::LoadFile("C:\dll.dll").GetTypes()
$attribute = [System.Type]::GetType("IgnoreAttribute")
foreach ($type in $types) { 
    $methods = $type.GetMethods()
    foreach ($method in $methods) { 
    if ($method .GetCustomAttributes($attribute).Length -gt 0) { 
        $method.Name
    }
}
Run Code Online (Sandbox Code Playgroud)