如何读出受保护的成员

时间:2010-12-02 02:59:33

标签: c# .net

我想访问一个类中的受保护成员。有一个简单的方法吗?

4 个答案:

答案 0 :(得分:9)

有两种方法:

  1. 创建要访问其受保护成员的类的子类。
  2. 使用反射。
  3. #1仅在您控制谁创建类的实例时才有效。如果已经构建了一个实例,那么#2是唯一可行的解​​决方案。

    就个人而言,我确保在使用反射之前,我已经用尽所有其他可能的机制来实现你的功能。

答案 1 :(得分:1)

我有时需要做到这一点。使用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);
    }

答案 2 :(得分:0)

如果您可以从拥有该受保护成员的类派生而不是您可以访问它 至于使用反射,this might help

答案 3 :(得分:0)

您是否为会员选择了合适的访问者?

  1. protected (C# Reference);
  2. public (C# Reference);
  3. private (C# Reference);
  4. internal (C# Reference)
  5. 您也可以将内部受保护的结合使用。
  6. 无论如何,受保护的访问者指定只能在派生类中访问成员。因此,如果您的目标是在派生类之外访问它,也许您应该考虑使用公共内部访问者??

    此外,这可以通过Reflection (C# and Visual Basic)来实现。

    另一方面,如果你真的想公开一个类的受保护的成员,我会尝试使用公共成员并返回对的引用保护通过它。

    但请在暴露受保护的成员之前,先问问自己,您的设计是否合适。它看起来像是一种设计气味。