派生类无法使用PropertyDescriptorCollection.SetValue访问受保护的setter

时间:2012-02-12 15:30:48

标签: c# reflection typedescriptor propertydescriptor

我已经在我的基类中设置了一个属性来拥有受保护的setter。 这工作正常,我能够在派生类的构造函数中设置属性 - 但是当我尝试使用PropertyDescriptorCollection设置此属性时,它将不会设置,但是使用该集合可以与所有其他属性一起使用。

我应该提一下,当我删除受保护的Access修饰符时,一切正常......但是当然现在它没有受到保护。谢谢你的任何意见。

 class base_a
{

 public  string ID { get; protected set; }
 public virtual void SetProperties(string xml){}
}

class derived_a : base_a
 {
   public derived_a()
    {
    //this works fine
     ID = "abc"
    }
   public override void SetProperties(string xml)
    {
      PropertyDescriptorCollection pdc = TypeDescriptor.GetProperties(this);
      //this does not work...no value set.
      pdc["ID"].SetValue(this, "abc");

      }
  }

2 个答案:

答案 0 :(得分:4)

TypeDescriptor不知道您是应该有权访问该属性设置器的类型调用它,因此您使用的PropertyDescriptor是只读的(您可以通过检查{来验证这一点) {3}})。当您尝试设置只读PropertyDescriptor的值时,没有任何反应。

要解决此问题,请使用正常反射:

var property = typeof(base_a).GetProperty("ID");

property.SetValue(this, "abc", null);

答案 1 :(得分:0)

试试这个

PropertyInfo[] props = TypeDescriptor
    .GetReflectionType(this)
    .GetProperties();
props[0].SetValue(this, "abc", null);

或者只是

PropertyInfo[] props = this
    .GetType()
    .GetProperties();
props[0].SetValue(this, "abc", null);

(您需要using System.Reflection;