I am using some 3rd party library that exposes some type (returned by a method).
This type has some protected fields i am interested in, however i am not able to use them since their visibility is protected.
Here is a simplification of the problem:
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 = ....
}
}
Is there any easy way to achieve this?
You can access the Field using this.Something
because your class is derived from class A
.
If you want to create a instance of the class A
, not your derived class, you can only access the field using 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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With