C#中事件的反射和私有委托字段 [英] Reflection and private delegate fields of events in c#
问题描述
我可能正在做一些愚蠢的事情,但是事情就这样了。
I'm probably doing something silly, but here it goes.
我正在尝试通过反思从公共事件中获取FieldInfo。
I'm trying to get the FieldInfo from a public event via reflection.
检查此功能:
public void PlotAllFields(Type type) {
BindingFlags all = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public;
FieldInfo[] fields = type.GetFields(all);
Console.WriteLine(type + "-------------------------");
foreach (var fieldInfo in fields) {
Console.WriteLine(fieldInfo.Name);
}
}
public class Bar : Foo {}
public class Foo {
public string Test;
public event EventHandler Event;
public event RoutedEventHandler RoutedEvent;
}
调用PlotAllFields(typeof(Foo));返回值:
The call PlotAllFields(typeof(Foo)); returns:
- 测试
- 事件
- RoutedEvent
调用PlotAllFields(typeof(Bar));返回:
The call PlotAllFields(typeof(Bar)); returns:
- 测试
我了解事件背后的代表是私有字段
,因此我无法在子类上访问它们。
I understand that the delegates behind the events are private fields so I can't access them on the subclass. So far so good.
然后我尝试了:PlotAllFields(typeof(FrameworkElement)); //来自WPF
Then I tried: PlotAllFields(typeof(FrameworkElement)); //from WPF
- _themeStyleCache
- _styleCache
- _templatedParent
- _templateChild
- _flags
- _flags2
- _parent
- _inheritableProperties
- MeasureRequest
- ArrangeRequest
- sizeChangedInfo >
- _parentIndex
- _parent
- _proxy
- _contextStorage
- _themeStyleCache
- _styleCache
- _templatedParent
- _templateChild
- _flags
- _flags2
- _parent
- _inheritableProperties
- MeasureRequest
- ArrangeRequest
- sizeChangedInfo
- _parentIndex
- _parent
- _proxy
- _contextStorage
嗯... FrameworkElement类的14个事件在哪里?
推荐答案
FrameworkElement不使用类似字段的事件,它会调用 AddHandler 和 RemoveHandler 。大多数情况下,他们没有附加处理程序,因此WPF使用的系统更加节省空间。例如,这是来自Reflector的Loaded事件:
FrameworkElement doesn't use field-like events, it makes calls to AddHandler and RemoveHandler. Most of the time they don't have handlers attached, so WPF uses a system that is more space-efficient. For example, here is the Loaded event, from Reflector:
public event RoutedEventHandler Loaded
{
add
{
base.AddHandler(LoadedEvent, value, false);
}
remove
{
base.RemoveHandler(LoadedEvent, value);
}
}
这篇关于C#中事件的反射和私有委托字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!