///如未特别说明,本人所发表的技术文章都为原创, 任何人引用都请包含本声明
///作者: csdn网名alias88,邮件:[email protected],qq:63343 ,欢迎加我
/// <summary>
///依导航路径调用对象成员方法,或返回对象其子、孙属性或字段成员.
///例子:
///获得表的第二列的名称
///getmember(datatable1.gettype(),"columns.item.name",datatable1,1)
///执行表的select方法,并返回可能的datarow数组
///getmember(datatable1.gettype(),"select",datatable1,"客户编号 = 'c0001')
///取活动表单的名称,静态成员不需传入obj
///getmember(typeof("system.windows.forms.form"),"activeform.name",null,null)
/// </summary>
/// <param name="type">获得此类型的子孙成员</param>
/// <param name="memberpath">子孙成员的路径描述,以点作为分隔符</param>
/// <param name="obj">如果成员是静态类型,则为null</param>
/// <param name="args">参数,注意此参数只能为memberpath最后一个成员使用</param>
/// <returns></returns>
public static object getmember(type type,string memberpath,object obj,object[] args)
{
if (memberpath==null || memberpath.trim ()=="")
throw new argumentexception ("缺少必需的参数","memberpath");
if (type==null )
throw new argumentexception ("缺少必需的参数","type");
type _objecttype=type;
object _object=obj;
object[] paras=null;
string[] strmember=memberpath.split ('.');
for (int i=0; i<strmember.length ;i++)
{
string membername=strmember[i];
if (i>=strmember.length-1 )
paras=args;
_object = _objecttype.invokemember(membername,
bindingflags.public | bindingflags.nonpublic |
bindingflags.instance | bindingflags.static |
bindingflags.getfield | bindingflags.getproperty |
bindingflags.invokemethod | bindingflags.ignorecase ,
type.defaultbinder, _object, paras);
if (_object!=null)
_objecttype=_object.gettype ();
else if (i<strmember.length-1)
throw new argumentnullexception(membername);
}
return _object;
}