访问类受保护的字段而不修改原始类

lys*_*cid 3 .net c# oop

我正在使用一些暴露某种类型的第三方库(由方法返回).

这种类型有一些我感兴趣的受保护字段,但我无法使用它们,因为它们的可见性受到保护.

以下是问题的简化:

public class A
    {
        protected object Something;

        public A Load()
        {
            return new A();
        }
    }

    public class ExtendedA : A
    {
        public void DoSomething()
        {
            // Get an instance.
            var a = Load();

            // Access protected fields (doesn't compile).
            a.Something = ....
        }
    }
Run Code Online (Sandbox Code Playgroud)

有没有简单的方法来实现这一目标?

dkn*_*ack 5

描述

您可以使用Field来访问Field,this.Something因为您的类来自class A.

如果要创建实例,而class A不是派生类,则只能使用反射访问该字段.

使用Reflection的示例

public class ExtendedA : A
{
    public void DoSomething()
    {
        // Get an instance.
        var a = Load();

        //get the type of the class
        Type type = a.GetType();
        BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic;

        // get the field info
        FieldInfo finfo = type.GetField("Something", bindingFlags);

        // set the value 
        finfo.SetValue(a, "Hello World!");

        // get the value
        object someThingField = finfo.GetValue(a);
    }
}
Run Code Online (Sandbox Code Playgroud)

更多信息