2

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

我应该提到,当我删除受保护的访问修饰符时,一切正常......但当然现在它不受保护。感谢您的任何意见。

 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");

      }
  }
4

2 回答 2

4

TypeDescriptor不知道您从应该有权访问该属性设置器的类型调用它,因此PropertyDescriptor您使用的是只读的(您可以通过检查IsReadOnly属性来验证这一点)。当您尝试设置 read-only 的值时PropertyDescriptor,什么也没有发生。

要解决此问题,请使用法线反射:

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

property.SetValue(this, "abc", null);
于 2012-02-12T16:13:37.963 回答
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;

于 2012-02-12T16:30:02.900 回答