What is wrong with this reflection code? GetFields () returns an empty array

C #, Net 2.0

Here's the code (I got all my domain related data, and it still returns an empty array):

using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { ChildClass cc = new ChildClass(); cc.OtherProperty = 1; FieldInfo[] fi = cc.GetType().GetFields(); Console.WriteLine(fi.Length); Console.ReadLine(); } } class BaseClass<T> { private int myVar; public int MyProperty { get { return myVar; } set { myVar = value; } } } class ChildClass : BaseClass<ChildClass> { private int myVar; public int OtherProperty { get { return myVar; } set { myVar = value; } } } } 
+15
reflection c # type-parameter
Jun 24 '09 at 20:30
source share
3 answers

Without parameters, GetFields() returns public fields. If you want non-public, use:

 cc.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic); 

or any suitable combination that you want - but you need to specify at least one of Instance and Static , otherwise it will not find. You can specify like all public fields to get everything:

 cc.GetType().GetFields(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public); 
+53
Jun 24 '09 at 20:32
source share

Since the field is private, you need to use the GetFields () overload, which allows you to specify BindingFlags.NonPublic .

To do this job, change it to:

 FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); 
+10
Jun 24 '09 at 20:32
source share

You need to specify that you want private (NonPublic) fields

Change to:

 FieldInfo[] fi = cc.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Instance); 
+5
Jun 24 '09 at 20:32
source share



All Articles