When I have this property in an abstract class:
public IList<Component> Components { get; private set; }
Then when I call:
p.GetSetMethod(true)
with p being a PropertyInfo object pointing to my property, I get null.
However if I change the property setter to protected, I can see it via reflection. Why is this? I don't seem to recall having this problem with non-abstract classes...
The following experimentation uncovered the issue for me. Note that the base class doesn't have to be abstract
to reproduce the problem.
public class Base
{
public string Something { get; private set; }
}
public class Derived : Base { }
public class MiscTest
{
static void Main( string[] args )
{
var property1 = typeof( Derived ).GetProperty( "Something" );
var setter1 = property1.SetMethod; //null
var property2 = typeof( Base ).GetProperty( "Something" );
var setter2 = property2.SetMethod; //non-null
bool test1 = property1 == property2; //false
bool test2 = property1.DeclaringType == property2.DeclaringType; //true
var solution = property1.DeclaringType.GetProperty( property1.Name );
var setter3 = solution.SetMethod; //non-null
bool test3 = solution == property1; //false
bool test4 = solution == property2; //true
bool test5 = setter3 == setter2; //true
}
}
What I learned from this and found surprising, is that the PropertyInfo
on the derived type is a different instance than the PropertyInfo
on the base type. Weird!
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