[英]How to get the value of a private static field from a class?
Is there any way to get value of private static field from known class using reflection?有没有办法使用反射从已知的 class 获取私有 static 字段的值?
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
.对于属性,将
type.GetField
更改为type.GetProperty
。 You can also access private methods in a similar fashion.您还可以以类似的方式访问私有方法。
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.
它创建了对此 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.如果这两个类要一起工作,请考虑将字段设为内部并在 [assembly:InternalsVisibleTo] 属性中添加协作 class 的程序集。
As stated above, you can probably use System.Type::GetMembers()
with BindingFlags
::NonPublic | BindingFlags::Static
如上所述,您可能可以将
System.Type::GetMembers()
与BindingFlags
::NonPublic | BindingFlags::Static
一起使用。 ::NonPublic | BindingFlags::Static
, but only if you have the right ReflectionPermission
. ::NonPublic | BindingFlags::Static
,但前提是您拥有正确的ReflectionPermission
。
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.但是,如果您在没有完全信任的系统上运行它,则 GetField 调用将失败,这将不起作用。
Try something like this:尝试这样的事情:
Type type = typeof(MyClass);
MemberInfo[] members = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);
I would think that is should work.我认为这应该可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.