我认为您是在谈论匿名方法,因此,您可以为此编写扩展方法并检查方法名称是否包含任何无效字符。由于编译器生成的方法包含无效字符,因此可以使用该功能来确定匿名方法。方法是否匿名:
public static bool IsAnonymous(this MethodInfo method)
{
var invalidChars = new[] {'<', '>'};
return method.Name.Any(invalidChars.Contains);
}
Run Code Online (Sandbox Code Playgroud)
测试:
Func<int> f = () => 23;
Console.Write(f.Method.IsAnonymous()); // true
Run Code Online (Sandbox Code Playgroud)
更优雅的方法是使用IsValidLanguageIndependentIdentifiermethod 验证方法名称,如下所示(此答案的方法):
public static bool IsAnonymous(this MethodInfo method)
{
return !CodeGenerator.IsValidLanguageIndependentIdentifier(method.Name);
}
Run Code Online (Sandbox Code Playgroud)
请记住,为了访问IsValidLanguageIndependentIdentifier方法,您需要包括System.CodeDom.Compiler名称空间。
| 归档时间: |
|
| 查看次数: |
719 次 |
| 最近记录: |