peS*_*HIr 5 .net attributes delegates
这与关于返回类型属性和匿名类的问题有关,但是对于匿名方法(或lambdas),但到目前为止,我发现这个确切的问题似乎还没有在stackoverflow上.
在我们使用CodeSmith生成的业务实体的代码中,我们现在具有[DebuggerNonUserCode]属性,因此它们不计入代码覆盖率结果.不幸的是,生成的代码使用匿名方法,这些方法现在仍然在代码覆盖中显示,其名称是Class.<>c__DisplayClass3c由于编译器实际处理它们的方式.
快速代码示例,更改名称和类型以保护无辜,可以这么说:
public delegate T ReturnSomething<T>();
public static T SafeCall<T>(T whenNotSupported, ReturnSomething<T> method)
{
T result;
try
{
result = method();
}
catch (NotSupportedException)
{
result = whenNotSupported;
}
return result;
}
public static void CodeExample()
{
string foo = SafeCall<string>("OOPS!", delegate
{
//throw new NotSupportedException();
return "Ok";
});
}
Run Code Online (Sandbox Code Playgroud)
有没有办法获取[DebuggerNonUserCode]这些方法的属性,以便我们可以从我们的代码覆盖率结果生成的代码中删除名称错位的匿名方法名称?或者我们是否需要重写生成的代码以不再使用匿名方法?
把[DebuggerNonUserCode]对method的参数SafeCall(之前的方法定义ReturnSomething<T>参数类型)不会编译,也许就不会做我们想,如果它会的.以下也不编译:
public static void CodeExample()
{
string foo = SafeCall<string>("OOPS!", [DebuggerNonUserCode] delegate
{
//throw new NotSupportedException();
return "Ok";
});
}
Run Code Online (Sandbox Code Playgroud)
我试图快速浏览一下CSharp语言规范,但是没有运气找到允许将属性应用于匿名方法(或lambdas)的语法.我想念它,还是这个(目前?)不可能......?
不幸的是,你不能.它列在C#3.0语言规范的第401页上:
可以在全局范围(指定包含的程序集或模块上的属性)和类型声明(第9.6节),类成员声明(第10.1.5节),接口成员声明(第13.2节)中指定属性, struct-member-declarations(§11.2),enum-member-declarations(§14.3),accessor-declarations(§10.7.2),event-accessor-declarations(§10.8.1)和formal-parameter-lists(§ 10.6.1).