あなたはリフレクションを使用する必要があります。
クラスの型を取得し、メソッドを取得して、正しい属性を持つ型を検索します。
MethodInfo[] methods = yourClassInstance.GetType()
.GetMethods()).Where(m =>
{
var attr = m.GetCustomAttributes(typeof(WorkItem), false);
return attr.Length > 0 && ((WorkItem)attr[0]).Value == 5555;
})
.ToArray();
必要に応じて複数の属性を確認できます。
これで、親クラスのインスタンスをこれらのメソッドを起動するターゲットとして使用するだけで済みます。あなたのメソッドはパラメータを持っている場合は
foreach (var method in methods)
{
method.Invoke(yourClassInstance, null);
}
は、パラメータを含むobject[]
でnull
を交換してください。あなたがしようとするためにここで
は完全な作業例です:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace ConsoleApplication7
{
public class MyAttribute : Attribute
{
public MyAttribute(int val)
{
Value = val;
}
public int Value { get; set; }
}
class Test
{
[MyAttribute(1)]
public void Method1()
{
Console.WriteLine("1!");
}
[MyAttribute(2)]
public void Method2()
{
Console.WriteLine("2!");
}
[MyAttribute(3)]
public void Method3()
{
Console.WriteLine("3!");
}
[MyAttribute(1)]
public void Method4()
{
Console.WriteLine("4!");
}
}
class Program
{
static void Main(string[] args)
{
var test = new Test();
var types = Assembly.GetAssembly(test.GetType()).GetTypes();
MethodInfo[] methods = test.GetType().GetMethods()
.Where(m =>
{
var attr = m.GetCustomAttributes(typeof(MyAttribute), false);
return attr.Length > 0 && ((MyAttribute)attr[0]).Value == 1;
})
.ToArray();
foreach (var method in methods)
{
method.Invoke(test, null);
}
}
}
}
あなたがテストに別のカテゴリを追加したくないのはなぜ?例えば。 '[TestCategory(" Cat A ")] [TestCategory(" WorkItem 5555 ")] public void SampleTest ...' – Gabrielius