已知函数名称,通过反射技术调用方法
public static T GetInvokeMethod<T>(string className, string methodName, object[] paras = null, bool isStatic = false)
{
try
{
Type type = Type.GetType(className);
if (type == null) return default(T);
if (isStatic)
{
object ret = type.InvokeMember(methodName, BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public, null, null, paras);
if (ret == null)
{
return default(T);
}
else
{
return (T)ret;
}
}
else
{
object obj = Activator.CreateInstance(type);
if (obj == null) return default(T);
MethodInfo method = null;
if (paras != null && paras.Length > 0)
{
Type[] paratypes = new Type[paras.Length];
for (int i = 0; i < paras.Length; i++)
{
paratypes[i] = paras[i].GetType();
}
method = type.GetMethod(methodName, paratypes);
}
else
{
method = type.GetMethod(methodName);
}
return (T)method?.Invoke(obj, paras);
}
}
catch
{
return default(T);
}
}
|