目前,我正在将一些旧代码移植到C# 7。由于语言的改变,我遇到了问题。在C# 5中,不捕获任何内容的lambda是静态的:
(handler.Method.IsStatic == true)在C# 7中,不再是这种情况,所有本地函数lambdas .都是本地函数。
因此,我需要以另一种方式了解Action是否捕获了一些值,以移植以下代码。
void add<U>(U target, Action<U> handler)
{
var hasHandlerCapturedSomething=!handler.Method.IsStatic;
if(hasHandlerCapturedSomething)throw new Exception("Only static handlers are allowed!");
//...
}发布于 2018-04-11 15:18:17
我最近的一次。如下所示。
static bool hasCapturedValues(Action a) { return isStatic(a.Method); }
static bool hasCapturedValues(System.Reflection.MethodInfo methodInfo)
{
var fields = methodInfo.DeclaringType.GetFields(BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Static |
BindingFlags.Instance |
BindingFlags.DeclaredOnly).ToList();
return methodInfo.IsStatic|| fields.All(f=>f.IsStatic);
}唯一不起作用的是下面的场景
class Foo{
int i;
void bar(){}
}
var foo=new Foo();
Action barAction=foo.bar;
Console.WriteLine(hasCapturedValues(barAction)); //print true这对我来说已经够近了,但如果有人有更好的东西。让我知道。
https://stackoverflow.com/questions/46643304
复制相似问题