使用与兄弟类的反射来设置属性c#

时间:2011-03-31 04:17:25

标签: c# reflection

namespace Stuff
{
    class MyStuff
    {
          ParmBlock MyParmSet = new ParmBlock();

          public void DoThis()
          {
            ...
            ParmBlock Parms = Get_The_Parms();
          }
          Private ParmBlock
          {
               Get
                 {
                    Return MyParmSet;
                 }
          }

     }
     Class ParmBlock
     {
           private string _Parm1;
           private string _Parm2;
           private int    _Parm3;

           public string Parm1
           {
              get
                 {
                    return _Parm1;            
                 }
              set
                 {
                    _Parm1 = Value;
                 }
           }

           public string Parm2
           {
              get
                 {
                    return _Parm2;            
                 }
              set
                 {
                    _Parm2 = Value;
                 }
           }

           public int Parm3
           {
              get
                 {
                    return _Parm3;            
                 }
              set
                 {
                    _Parm3 = Value;
                 }
           }     
      }  
 }

我的问题是我可以对mystuff使用Activator.Createinstance并且效果很好,但我如何在ParmBlock中设置参数?到目前为止,我所尝试的一切都失败了,我在这里慢慢疯狂.......

谢谢

1 个答案:

答案 0 :(得分:2)

使用通过调用类型本身的GetProperty()调用获得的PropertyInfo。然后,您可以使用PropertyInfo.GetValue()和PropertyInfo.SetValue方法。

void example( Object target, string propertyName )
{
    PropertyInfo info = typeof(target).GetProperty( propertyName );

    object value = info.GetValue( target, new object[] {} );
}

HTH

马里奥

相关问题