【发布时间】:2012-05-14 22:48:31
【问题描述】:
我确信论坛上的某个地方已经有答案了,但我至今没能找到它。根据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() 方法。
【问题讨论】:
-
我认为这只有在您使用表达式时才有可能,例如。
System.Linq.Expressions.Expression<Action>。然后可以将body转换为MethodCallExpression,并使用里面的MethodInfo对象来查询属性... -
您的委托变成编译器生成的类,派生自
MulticastDelegate之类的东西,其中包含您的方法信息。我认为可以通过反射得到它。 -
我已经在类似的场景中试验过这种模式。我发现它非常脆弱。仅供参考。
标签: c# reflection delegates attributes