根据给定的对象和路径,获得其子孙成员

类别:.NET开发 点击:0 评论:0 推荐:

 /// <summary>
  /// 根据给定的对象和路径,获得其子孙成员
  /// </summary>
  /// <param name="pTopObject">要获得的成员是此对象的子孙,一般为Form</param>
  /// <param name="pObjPath">依此路径获取,例如: TextBox1 或TextBox1.Size</param>
  /// <param name="Index">用索引化属性的可选索引值返回</param>
  /// <returns>子孙</returns>
  public static object GetMember(object pTopObject, string pObjPath,object[] Index)
  {
   string[] strMember;
   string MemberName="";
   object obj=null;
   Type objType=null;

   try
   {
    strMember=pObjPath.Split ('.');
    for (int i=0; i<strMember.Length && strMember[i]!="" ;i++)
    {
     if (i==0)
     {
      obj=(object)pTopObject;
      objType=pTopObject.GetType ();
     }
     MemberName=strMember[i];

     obj = (object) objType.InvokeMember(MemberName,
      BindingFlags.Public | BindingFlags.NonPublic |BindingFlags.IgnoreCase |
      BindingFlags.Instance | BindingFlags.Static| BindingFlags.GetField |  BindingFlags.GetProperty , null, obj, null);
     if (obj!=null)     objType=obj.GetType ();
     else throw new Exception ("不能根据:" + pObjPath + "获得" + pTopObject.ToString() + "的成员:" + MemberName);
    }
    return obj;

   }
   catch ( System.Exception ex  ){ throw new Exception ("获取 " + pObjPath  + " 的成员:" + MemberName + "时发生错误:\n" + ex.Message );  }
  
  }

本文地址:http://com.8s8s.com/it/it44002.htm