I have 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 I move property definition to class Foo then I works as expected. Is this a bug in .NET?
You can achieve it by getting the PropertyInfo on the declaring type of the property, simple extension method could 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 does...
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();
}
}
This is by design. The FooBase property setter is not accessible in the Foo class, no matter what you try:
public class Foo : FooBase {
void Test() {
Prop = new object(); // No
((FooBase)this).Prop = new object(); // No
}
}
You'll have to use typeof(FooBase).GetProperty("Prop") in your code.
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