Can I use PrivateObject class or Reflection to access a field in a private class?
If i have a private class
Class A
{
public static strin开发者_开发问答g foo;
}
Can i use reflection to access that static field? Assuming of course i cannot change the code...
The problem i have is that the Class is defined in a different Namespace than i am in.
lets say I am in the Test namespace, and i have a reference to a DLL with the FOO namespace.
namespace FOO
{
Class A
{
public static string bar;
}
}
I want to access the bar field in the class A from namespace TEST.
Yes, you can. You'll need to get the Type
- how you do that will depend on the exact nature of your app; Assembly.GetType(string)
would be one option, for example. After that, you get the FieldInfo
with Type.GetField
and then ask the field for its value, using null
as the target as it's a static field.
What finally worked for me was the Assembly approach:
assembly = typeof(Class B).Assembly; //Class B is in the same namespace as A
Type type = assembly.GetType("FOO.A");
string val = (string) type.GetField("bar",
BindingFlags.Public | BindingFlags.Static).GetValue(null);
this is intentionally verbose so you'll get what is happening step by step. It checks all the fields in type A and looks for one named "foo".
EDIT: it works for A in a different namespace too.
namespace DifferentNamespace
{
class A
{
public static string foo = "hello";
}
}
class Program {
static void Main(string[] args) {
Type type = typeof(DifferentNamespace.A);
FieldInfo[] fields = type.GetFields();
foreach (var field in fields)
{
string name = field.Name;
object temp = field.GetValue(null); // Get value
// since the field is static
// the argument is ignored
// so we can as well pass a null
if (name == "foo") // See if it is named "foo"
{
string value = temp as string;
Console.Write("string {0} = {1}", name, value);
}
Console.ReadLine();
}
}
}
Try
object value = typeof (Program).GetFields(BindingFlags.Static | BindingFlags.Public)
.Where(x => x.Name == "foo").FirstOrDefault()
.GetValue(null);
精彩评论