Getting set accessor for property in abstract class, not possible?
Given the class':
public abstract class Abstrac开发者_运维问答tEntity
{
public virtual Guid Id { get; private set; }
}
public class Entity
{
public virtual Guid Id { get; private set; }
}
And a PropertyInfo for the property 'Id'.
When calling the method:
PropertyInfo.GetAccessors()
It returns both the get-method and the set-method when the class is not abstract (Entity), but only the get-method when the class is abstract (AbstractEntity).
Why is this? And is there another way to get the set-method from a property with a private set?
If you want to get the MethodInfo for the set, you can. That doesn't mean you can actually use it, as Kevin point in his answer.
Type t = typeof(AbstractEntity);
MethodInfo[] mi = t.GetProperty("Id").GetAccessors(true);
In an abstract class, you can't instantiate it. Barring reflection, there is nothing that can call the private setter. In reflection, you still have to instantiate the class (not including static items) to access properties call methods etc, and this can't be done in an abstract class. Being able to access it wouldn't grant you anything, and in fact nothing can access it to use it.
精彩评论