PropertyInfo.GetSetMethod (true) does not return a method for properties from the base class

I have the following test program:

public class FooBase { public object Prop { get { return null; } private set { } } } public class Foo :FooBase { } class Program { static void Main(string[] args) { MethodInfo setMethod = typeof(Foo).GetProperty("Prop").GetSetMethod(true); if (setMethod==null) Console.WriteLine("NULL"); else Console.WriteLine(setMethod.ToString()); Console.ReadKey(); } } 

And it shows "NULL" if I run it. If you move the property definition to the Foo class, then I will work as expected. Is this a bug in .NET?

+6
source share
3 answers

You can achieve this by getting PropertyInfo in a declaring property type, a simple extension method can be ...

 public static class Extensions { public static MethodInfo GetSetMethodOnDeclaringType(this PropertyInfo propertyInfo) { var methodInfo = propertyInfo.GetSetMethod(true); return methodInfo ?? propertyInfo .DeclaringType .GetProperty(propertyInfo.Name) .GetSetMethod(true); } } 

then your calling code ...

 class Program { static void Main(string[] args) { MethodInfo setMethod = typeof(Foo) .GetProperty("Prop") .GetSetMethodOnDeclaringType(); if (setMethod == null) Console.WriteLine("NULL"); else Console.WriteLine(setMethod.ToString()); Console.ReadKey(); } } 
+6
source

This is by design. The FooBase property setter is not available in the Foo class, regardless of what you are trying:

 public class Foo : FooBase { void Test() { Prop = new object(); // No ((FooBase)this).Prop = new object(); // No } } 

You will need to use typeof (FooBase) .GetProperty ("Prop") in your code.

+5
source

EDIT

Unfortunately,

You are correct in your comment below. The error is different. There is no method set in the Foo class, so it does not return a method. He is not, because he is private in the base class.

+3
source

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


All Articles