我想访问类中的受保护成员。有简单的方法吗?
仅当您控制类实例的创建者时,#1 才有效。如果已经构造好一个实例并交给您处理,则 #2 是唯一可行的解决方案。
个人建议,在使用反射之前,先确保已经尝试了所有其他可能的实现机制。
我有时需要做到这一点。当使用WinForms时,您希望访问系统类中的某些值,但由于它们是私有的,无法访问。为了解决这个问题,我使用反射来访问它们。例如...
// Example of a class with internal private field
public class ExampleClass
{
private int example;
}
private static FieldInfo _fiExample;
private int GrabExampleValue(ExampleClass instance)
{
// Only need to cache reflection info the first time needed
if (_fiExample == null)
{
// Cache field info about the internal 'example' private field
_fiExample = typeof(ExampleClass).GetField("example", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.GetField);
}
// Grab the internal property
return (int)_fiExample.GetValue(instance);
}
你是否选择了正确的成员访问器?
毫无疑问,protected访问器指定一个成员只能在派生类中访问。因此,如果你的目标是在派生类之外访问它,也许你应该考虑使用public或internal访问器!?
此外,这可以通过 Reflection (C# 和 Visual Basic) 实现。