How to access private field?

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);
 
Z

zlf

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.
 
J

Joanna Carter [TeamB]

"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
 
N

Nicholas Paldino [.NET/C# MVP]

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top