views:

78

answers:

2

Given this class

public partial class Default : Page
{
    private IRepository repo;
    ...
}

I want to find and set the private repo field. Is that possible?

UPDATE

I tried using the GetFields(BindingFlags.NonPublic), it returns {System.Reflection.FieldInfo[0]}.

UPDATE II

I tried using the GetFields(BindingFlags.NonPublic | BindingFlags.Instance) , it returns all the fields of the Page but not repo.

+3  A: 

Use the GetFields overload that allows you to specify flags:

GetFields(BindingFlags.NonPublic | BindingFields.Instance)

HTH,
Kent

Kent Boogaart
I've taken the liberty of adding BindingFlags.Instance. If you specify no flags you get (BindingFlags.Public | BindingFlags.Instance), but if you specify any you get only the ones you specify, so you need either Instance or Static to get any results.
Greg Beech
Don't forget that it will only return the fields for the current type, you may have to walk down the hierarchy if the field is defined in a base class.
Jb Evain
Jb Evain: When I change 'repo' to public it does work, just when I change it to private it doesn't appear.
CD
A: 

Hi, you can use the following code :

MemberInfo[] mi = System.Runtime.Serialization.FormatterServices.GetSerializableMembers(MyType);

and convert FieldInfo fi = (FieldInfo) mi[i]; this code return Serializable Members (privates)

Montasser Ben Ouhida
For using your solution my page needs to be Serializable, is this the only way??
CD
yes, I think there are another way, it's using debugging service like Quick Watch in Visual Studio, but you need the .pdb files
Montasser Ben Ouhida