您將不得不使用反射。
獲取你的類的類型,獲取它的方法,然後搜索那些具有正確屬性的類。
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