Get inherited private setter property

The following are my codes:

class Foo { public string Bar { get; private set; } } 

and

 var prop = typeof(Foo).GetProperty("Bar"); if (prop != null) { // The property exists var setter = prop.GetSetMethod(true); if (setter != null) { // There a setter Console.WriteLine(setter.IsPublic); } } 

yes, as you can imagine, this works perfectly right. but when the inheritance comes, everything is different:

 class Foo { public string Bar { get; private set; } } class A : Foo { } 

Of course, I changed this line:

 var prop = typeof(Foo).GetProperty("Bar"); 

to

 var prop = typeof(A).GetProperty("Bar"); 

then the installer gets null and the console doesn't print anything!

So why?

btw, is there any workaround to make this happen or be in a completely different way?

Any help would be appreciated. thanks.

+4
source share
3 answers

So why?

As for A , Bar is read-only - you cannot invoke the installer from A , so it makes sense that there is no setter when you request a property regarding A

One option is to use the anchor flags only to request declared properties and pave the way to the inheritance chain until you find the actual property declaration. It is a little strange that you should do this, but it makes some sense, since the property really differs depending on whether you come to it from the context of the declaring class or not.

I am surprised at this behavior, but not shocked.

+2
source

The general solution is to call

 var prop = GetType().GetProperty("Bar").DeclaringType.GetProperty("Bar"); 

Which is not very intuitive, I agree.

+3
source

You can set a private property with reflection by simply using the SetValue method in the property information, even if you cannot get the set method.

0
source

Source: https://habr.com/ru/post/1488622/


All Articles