Gui*_*ume 6 c# delegates anonymous-methods
这是C#4.0.
我有一类商店WeakReference的一些作者Action,就好比:
public class LoremIpsum
{
private Dictionary<Type, List<WeakReference>> references = new Dictionary<Type, List<WeakReference>>();
public void KeepReference<T>(Action<T> action)
{
if (this.references.ContainsKey(typeof(T)))
{
this.references[typeof(T)].Add(new WeakReference(action));
}
else
{
this.references.Add(typeof(T), new List<WeakReference> { new WeakReference(action) });
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个类有另一个允许执行Action稍后传递给它的方法,但在这个问题中它并不重要.
我以这种方式使用这个类:
public class Foobar
{
public Bar Bar { get; set; }
public void Foo(LoremIpsum ipsum)
{
ipsum.KeepReference<Bar>((b) => { this.Bar = b; });
ipsum.KeepReference<Bar>(this.Whatever);
}
public void Whatever(Bar bar)
{
// Do anything, for example...:
this.Bar = bar
}
}
Run Code Online (Sandbox Code Playgroud)
Bar 在我的申请中是第三类.
我的问题:
在该KeepReference方法中,我如何知道Action传入的参数是引用匿名方法(this.Bar = b;)还是具体方法(this.Whatever)?
我检查了属性action.我找不到任何属性action(比如IsAbstract)IsAnonymous.基础类型是MethodInfo有意义的,因为编译后我可以在ildasm中看到匿名方法"成为"正常的方法Foobar.在ildasm我也可以看到匿名方法不是一个完整的粉红色正方形,而是一个被粉红色包围的白色方块,在它的定义中,它调用了一些CompilerServices类,但我不知道如何在C#中利用它.我相信我们可以了解它的真实本质action.我错过了什么?
为了对这个问题有一个“接受的”答案,我按照 Michael Kj\xc3\xb6rling 在他对我的问题的第一个评论中给出的链接进行了操作。
\n\nif (action.Target.GetType().GetMethods().Where(method => method.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any()).Contains(action.Method))\n{\n // ...\n}\nRun Code Online (Sandbox Code Playgroud)\n