On Jan 24, 8:07 am, v-l...@online.microsoft.com (Linda Liu[MSFT])
wrote:
> No, we have no way to get the values of PRIVATE fields of an object from
> outside.
Yes, we do. If you call GetFields with the overload taking a
BindingFlags parameter, you can request non-public fields. For
instance, let's see what System.String contains:
using System;
using System.Reflection;
class Test
{
static void Main(string[] args)
{
foreach (FieldInfo fi in typeof(string).GetFields
(BindingFlags.Instance | BindingFlags.NonPublic))
{
Console.WriteLine ("{0} ({1}) = {2}",
fi.Name,
fi.FieldType,
fi.GetValue("foo"));
}
}
}
Resuts:
m_arrayLength (System.Int32) = 4
m_stringLength (System.Int32) = 3
m_firstChar (System.Char) = f
This depends on having the required permissions, of course.
Jon
Linda Liu[MSFT] - 28 Jan 2008 06:45 GMT
Thanks Jon for correcting me! I was ignoring the BindingFlags parameter!
Hi Flomo,
How about the problem now?
To get what you want, you can get the value of this field by calling the
GetFields method on the type of this object passing BindingFlags.Instance
plus BindingFlags.NonPublic as the parameter and then calling the GetValue
method on the FieldInfo instances.
The following is a sample.
class MyClass
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
}
private void Form1_Load(object sender, EventArgs e)
{
MyClass obj = new MyClass();
obj.Name = "aa";
FieldInfo[] fis = obj.GetType().GetFields(BindingFlags.Instance |
BindingFlags.NonPublic);
object value = fis[0].GetValue(obj);
}
If you have any question, please feel free to let us know.
Sincerely,
Linda Liu
Microsoft Online Community Support
Linda Liu[MSFT] - 31 Jan 2008 02:36 GMT
Hi Flomo,
I am reviewing this post and would like to know the status of this issue.
If you have any question, please feel free to let me know.
Thank you for using our MSDN Managed Newsgroup Support Service!
Sincerely,
Linda Liu
Microsoft Online Community Support