我确信在论坛的某个地方已经有了答案,但到目前为止我还没有找到它。根据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:07:13
如果将TestThat(() => TargetHasOneTeam()) (将代理包装到另一个操作中)更改为TestThat(TargetHasOneTeam),并按如下方式更改TestThat:
public static void TestThat(TestCaseBase.Action action)
{
TestCaseResult result = action.Invoke();
var attrs = action.GetInvocationList()[0].Method.GetCustomAttributes(true);
// I want to get the value of the TestDescription attribute here
}会给你你想要的。
使用表达式:
public static void TestThat(Expression<Func<TestResult>> action)
{
var attrs = ((MethodCallExpression)action.Body).Method.GetCustomAttributes(true);
var result = action.Compile()();
}发布于 2012-05-15 06:54:12
在这种特殊情况下,它基本上是无法访问的。您正在创建一个lambda,它执行所讨论的方法。该lambda最终导致生成一个新方法,该方法最终成为Action委托的参数。这种方法与TargetHasOneTeam没有关系,只有当你深入研究正文中的IL指令时,它才是明显的。
你可以跳过lambda,在这里做一个方法组转换。
TestThat(TargetHasOneTeam);现在,TargetHasOneTeam被直接分配给委托实例,并且将在Delegate::MethodInfo属性中可见。
注意:一般来说,对于您遇到的问题来说,这不是一个好主意。方法的属性不应该影响它满足委托实例化的能力。如果可能的话,我会避免这种类型的检查。
发布于 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
复制相似问题