问题
I'm probably doing something silly, but here it goes.
I'm trying to get the FieldInfo from a public event via reflection.
Check this function:
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;
}
The call PlotAllFields(typeof(Foo)); returns:
- Test
- Event
- RoutedEvent
The call PlotAllFields(typeof(Bar)); returns:
- Test
I understand that the delegates behind the events are private fields so I can't access them on the subclass. So far so good.
Then I tried: PlotAllFields(typeof(FrameworkElement)); //from WPF
- _themeStyleCache
- _styleCache
- _templatedParent
- _templateChild
- _flags
- _flags2
- _parent
- _inheritableProperties
- MeasureRequest
- ArrangeRequest
- sizeChangedInfo
- _parentIndex
- _parent
- _proxy
- _contextStorage
Well... Where are the 14 events of FrameworkElement class???
回答1:
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);
}
}
回答2:
try these binding flags
BindingFlags.Default |
BindingFlags.FlattenHierarchy |
BindingFlags.Instance |
BindingFlags.NonPublic |
BindingFlags.Public
http://msdn.microsoft.com/query/dev10.query?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.REFLECTION.BINDINGFLAGS);k(TargetFrameworkMoniker-%22.NETFRAMEWORK,VERSION%3dV3.5%22);k(DevLang-CSHARP)&rd=true
来源:https://stackoverflow.com/questions/3618085/reflection-and-private-delegate-fields-of-events-in-c-sharp