我确信在论坛的某个地方已经有了答案,但到目前为止我还没有找到它。根据this example,我将匿名方法与委托结合使用,以便具有不同参数但返回类型相同的不同方法,所有方法都作为函数参数工作:
public delegate TestCaseResult Action();
...
[TestDescription("Test whether the target computer has teaming configured")]
public TestCaseResult TargetHasOneTeam()
{
// do some logic here and return
// TestCaseResult
}
[TestDescription("Test whether the target computer has the named team configured")]
public TestCaseResult TargetHasNamedTeam(string teamName)
{
// do some logic here and return
// TestCaseResult
}
...
public static void TestThat(TestCaseBase.Action action)
{
TestCaseResult result = action.Invoke();
// I want to get the value of the TestDescription attribute here
}
...
// usage
TestThat(() => TargetHasOneTeam());
TestThat(() => TargetHasNamedTeam("Adapter5"));正如您从示例中看到的,我非常希望能够从TestThat()函数中获取TestDescriptionAttribute属性。我已经查看了包含我的方法的Action参数,但是还没有“找到”我的TargetHasOneTeam()方法。
发布于 2012-05-15 07:03:27
您可以使用Attribute.GetCustomAttribute获取任何成员的属性。首先检查是否定义了该属性。例如:
public static void TestThat(TestCaseBase.Action action)
{
TestCaseResult result = action.Invoke();
if(System.Attribute.IsDefined(action.Method, typeof(TestDescriptionAttribute)))
{
var attribute = (TestDescriptionAttribute)System.Attribute.GetCustomAttribute(action.Method,
typeof(TestDescriptionAttribute));
Console.WriteLine(attribute.TestDescription);
}
}https://stackoverflow.com/questions/10592048
复制相似问题