public class Test
{
public int[] GetData(int[] pArgs)
{
return pArgs;
}
public decimal[] GetData1(decimal[] pArgs)
{
return pArgs;
}
}
以上方法,在使用CreateInstance调用时将会出现很多麻烦,并且InvokeMethod不一定能够成功。
问题1:参宿的传入:因为调用方法时,必须完全匹配各个参数,所以都不能用object[].
问题2:返回结果如何解开为数组
解决:
1:通过使用List<>特性,使用CreateInstance创建一个指定类型的实例,这样返回的ToArray肯定是指定类型的数组
2:使用Array来默认转换返回的结果数组
Code
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace Test_WebApp
{
public class SuperConvert
{
private object m_InstanceOfObj;
private MethodInfo m_AddMethod;
private MethodInfo m_ToArrayMethod;
public SuperConvert(string pTypeName)
{
//create by list<>
string vTypeString = string.Format("System.Collections.Generic.List`1[[{0}, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]", pTypeName);
this.m_InstanceOfObj = Activator.CreateInstance(Type.GetType(vTypeString));
this.m_AddMethod = this.m_InstanceOfObj.GetType().GetMethod("Add");
this.m_ToArrayMethod = this.m_InstanceOfObj.GetType().GetMethod("ToArray");
}
public void Add(object pValue)
{
this.m_AddMethod.Invoke(this.m_InstanceOfObj, new object[] { pValue });
}
public object ToArray()
{
return this.m_ToArrayMethod.Invoke(this.m_InstanceOfObj, null);
}
}
}
2.MethodInfo vMethodInfo = vObjInstance.GetType().GetMethod("MethodName");
object vRtn = vMethodInfo.Invoke(vObjInstance, new object[]{123,345});
Array vRtnList = (Array)vRtn;