How to access private field?

  • Thread starter Thread starter zlf
  • Start date Start date
Z

zlf

Hi,
I am trying to access private field by code below. But it runs with
error.
Please tell me what's the problem or any method that may allow me to
access private field. Thank you


class Love
{
private string Name;
}

Love love = new Love();
Type type = love.GetType();
Object obj = type.InvokeMember(null,
BindingFlags.DeclaredOnly |
BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance |
BindingFlags.CreateInstance, null, null, args);

string
str=(string)type.InvokeMember("Name",BindingFlags.GetProperty,null,obj,null);
 
I have got the solution just now.

Love obj = new Love("test");
Type type = typeof(Love);

object obj2 = type.InvokeMember("Name",
BindingFlags.GetField | BindingFlags.NonPublic |
BindingFlags.Instance, null, obj, null);

Console.WriteLine(obj2);

test should be the output.
 
"zlf" <[email protected]> a écrit dans le message de %[email protected]...

| Hi,
| I am trying to access private field by code below. But it runs with
| error.
| Please tell me what's the problem or any method that may allow me to
| access private field. Thank you

Look at Type.GetField(...) and FieldInfo.GetValue(...).

Joanna
 
What is the exception you are getting?

It looks a little redundant to me. First, you are trying to call
InvokeMember, but you are not passing a member to invoke! Also, I would
think that this is only for executing properties and methods, not for
fetching a value from a field.

I would recommend getting the FieldInfo that corresponds to the field
you want the value of, and then calling the GetValue/SetValue methods to get
the value.

Hope this helps.
 
Back
Top