这是 C# 4.0。
我有一个类,它存储了一些 Action
的 WeakReference
,就像这样:
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) });
}
}
}
这个类还有另一个方法,允许稍后执行传递给它的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
}
}
Bar
是我的应用程序中的第三类。
我的问题:
在KeepReference
方法中,我如何知道传入参数的Action
是指匿名方法(this.Bar = b;
)还是一个具体的方法(this.Whatever
)?
我检查了action
的属性。我找不到任何关于action
的属性(例如IsAbstract
)或者IsAnonymous
之类的。底层类型是MethodInfo
,这很有意义,因为编译后我可以在ildasm中看到匿名方法“变成”了Foobar
上的普通方法。在ildasm中,我还可以看到匿名方法不是一个完整的粉色正方形,而是被粉色包围的白色正方形,在其定义中调用了一些CompilerServices类,但我不知道如何在C#中利用它。我相信有可能了解action
的真实性质。我错过了什么?