C# 如何从类中获取私有静态字段的值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/628666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 10:57:05  来源:igfitidea点击:

How to get the value of a private static field from a class?

c#reflection

提问by chief7

Is there any way to get value of private static field from known class using reflection?

有没有办法使用反射从已知类中获取私有静态字段的值?

采纳答案by configurator

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.GetFieldto type.GetProperty. You can also access private methods in a similar fashion.

这是一个领域。对于属性,更改type.GetFieldtype.GetProperty。您还可以以类似的方式访问私有方法。

回答by David Pokluda

Try something like this:

尝试这样的事情:

Type type = typeof(MyClass);
MemberInfo[] members = type.GetMembers(BindingFlags.NonPublic | BindingFlags.Static);

I would think that is should work.

我认为这应该有效。

回答by i_am_jorf

As stated above, you can probably use System.Type::GetMembers()with BindingFlags::NonPublic | BindingFlags::Static, but only if you have the right ReflectionPermission.

如上所述,您可能可以使用System.Type::GetMembers()with ,但前提是您拥有正确的.BindingFlags::NonPublic | BindingFlags::StaticReflectionPermission

回答by Reed Copsey

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 调用将失败,这将不起作用。

回答by John Saunders

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 internaland adding the assembly of the cooperating class in an [assembly:InternalsVisibleTo] attribute.

如果这两个类要一起工作,请考虑将字段设为内部并在 [assembly:InternalsVisibleTo] 属性中添加协作类的程序集。