简体   繁体   中英

Get protected property value of base class using reflection

I would like to know if it is possible to access the value of the ConfigurationId property which is located in the base class of the object and it's private. I have tried to do it with reflection with no luck. 在此处输入图像描述

To access ConfigurationId property i have used following code:

SubsetController controller = new SubsetController(new CConfigRepository(new FakeDataContextRepository()));

var myBaseClassProtectedProperty=
            controller.GetType().BaseType
                .GetProperty("CCITenderInfo", BindingFlags.NonPublic | BindingFlags.Instance)
                .GetValue(controller);

var myProtectedProperty =
            CCITenderInfo.GetType()
                .GetProperty("ConfigurationId", BindingFlags.Public |     BindingFlags.Instance)
                .GetValue(myBaseClassProtectedProperty);

Assuming the following parent and child class:

class BaseClass
{
    private string privateField = "I'm Private";
}

class ChildClass : BaseClass
{

}

You can read privateField 's value from a ChildClass instance using reflection like this:

ChildClass childInstance = new ChildClass();
object privateFieldValue = childInstance.GetType().BaseType
    .GetField("privateField", BindingFlags.NonPublic | BindingFlags.Instance)
    .GetValue(childInstance);
Console.WriteLine(privateFieldValue); // I'm Private

To add to this answer - you should use the Instance and NonPublic binding flags for sure, but you should also ensure that you are actually referencing properties and not fields .

Eg if you have

protected string Andrew;

You will not be able to get this via GetProperty , no matter what binding flags you use. Why - because it is a field, and not a property...

To fix this, just change it to

protected string Andrew {get;set;}

and then you can use the GetProperty method.

Yes, this is possible with reflection.

However, in order to look up nonpublic members, you'll need to use the reflection overload which take BindingFlags parameters. In order to look up private members, you'll also need to access via the typeof the base class, even when using BindingFlags.FlattenHierarchy . This also means you'll need to use the exact binding, however note that contradictory flags (such as using both NonPublic and Public ) are valid and will return either at that point.

Be aware that the very need to look up nonpublic members could be considered code smell, and you should do so very carefully. Also be aware that nonpublic members are not guaranteed to have the same names across different versions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM