问题
Is there any way to get value of private static field from known class using reflection?
回答1:
Yes.
Type type = typeof(TheClass);
FieldInfo info = type.GetField(name, BindingFlags.NonPublic | BindingFlags.Static);
object value = info.GetValue(null);
This is for a field. For a property, change type.GetField to type.GetProperty. You can also access private methods in a similar fashion.
回答2:
I suppose someone should ask whether this is a good idea or not? It creates a dependency on the private implementation of this static class. Private implementation is subject to change without any notice given to people using Reflection to access the private implementation.
If the two classes are meant to work together, consider making the field internal and adding the assembly of the cooperating class in an [assembly:InternalsVisibleTo] attribute.
回答3:
As stated above, you can probably use System.Type::GetMembers() with BindingFlags::NonPublic | BindingFlags::Static, but only if you have the right ReflectionPermission.
回答4:
If you have full trust, you should be able to do:
Type t = typeof(TheClass);
FieldInfo field = t.GetField("myFieldName", BindingFlags.NonPublic | BindingFlags.Static);
object fieldValue = field.GetValue(myObject);
However, if you run this on a system without full trust, the GetField call will fail, and this won't work.
回答5:
Try something like this:
Type type = typeof(MyClass);
MemberInfo[] members = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);
I would think that is should work.
来源:https://stackoverflow.com/questions/628666/how-to-get-the-value-of-a-private-static-field-from-a-class