【发布时间】:2016-02-12 12:13:21
【问题描述】:
这是我的示例方法
[TestStep("Do something")]
private void DoSomething()
{
}
每个看起来像上面的方法都以需要记录方法参数的方式执行:
private void LogStep(Action action)
{
string stepName = "[" + action.Method.Name + "] ";
var descr = Attribute.GetCustomAttribute(action.Method, typeof(TestStepAttribute)) as TestStepAttribute;
if (descr == null)
{
this.TestLog.AddWarningMessage(
(action.Method.DeclaringType == null ? string.Empty : action.Method.DeclaringType.FullName + ".") + action.Method.Name
+ ": missing description");
return;
}
stepName += descr.Description;
this.TestLog.EndGroup();
this.TestLog.BeginGroup(stepName);
}
我遇到了一个问题。像这样执行 LogStep
LogStep(DoSomething)
完美运行,但是当我使用 lambda 表达式执行它时
LogStep(() => DoSomething())
它告诉我Action 中没有TestStepAttribute 类型的属性。
乍一看,它似乎类似于How do I get the custom attributes of a method from Action<T>?,但就我而言,我既不能将Action 的类型更改为Expression<Action>,也不知道方法名称。
任何建议都会有所帮助。
【问题讨论】:
-
编写一个接受表达式树的方法版本(与委托不同,它很容易检查)。否则,除非您想开始深入研究 IL 操作码,否则您将不走运。
-
你的第一个执行示例不应该是
LogStep(DoSomething)吗? (没有“()”)