public class Foo
{
private Bar FooBar {get;set;}
private class Bar
{
private string Str {get;set;}
public Bar() {Str = "some value";}
}
}
If I've got something like the above and I have a reference to Foo, how can I use reflection to get the value Str out Foo's FooBar? I know there's no actual reason to ever do something like this (or very very few ways), but I figure there has to be a way to do it and I can't figure out how to accomplish it.
edited because I asked the wrong question in the body that differs from the correct question in the title
This is how you can write to the private property by using Reflection: //Example class public class Person { public string Name { get; private set; } } var person = new Person(); //Cannot do this due to the private set:er: //person.Name = "Foo"; //Set value by using Reflection: person. GetType(). GetProperty("Name").
Occasionally, when writing C# unit tests, you will come across classes with private members that need to be accessed or modified to properly test the system. In these cases, reflection can be used to gain access to private members of a class.
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property.
Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.
You can use the GetProperty
method along with the NonPublic
and Instance
binding flags.
Assuming you have an instance of Foo
, f
:
PropertyInfo prop =
typeof(Foo).GetProperty("FooBar", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo getter = prop.GetGetMethod(nonPublic: true);
object bar = getter.Invoke(f, null);
Update:
If you want to access the Str
property, just do the same thing on the bar
object that's retrieved:
PropertyInfo strProperty =
bar.GetType().GetProperty("Str", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo strGetter = strProperty.GetGetMethod(nonPublic: true);
string val = (string)strGetter.Invoke(bar, null);
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