.net 反射,从方法获取返回值
我们如何验证一个方法并从反射中获得返回值.net 反射,从方法获取返回值,.net,reflection,.net,Reflection,我们如何验证一个方法并从反射中获得返回值 Type serviceType = Type.GetType("class", true); var service = Activator.CreateInstance(serviceType); serviceType.InvokeMember("GetAll", BindingFlags.InvokeMethod, Type.DefaultBinder, service, null); “返回值 类型:System.Object 表示被调用成
Type serviceType = Type.GetType("class", true);
var service = Activator.CreateInstance(serviceType);
serviceType.InvokeMember("GetAll", BindingFlags.InvokeMethod, Type.DefaultBinder, service, null);
“返回值
类型:System.Object
表示被调用成员的返回值的对象。“
“返回值
类型:System.Object
表示被调用成员的返回值的对象。“将InvokeMember结果强制转换为方法调用实际返回的类型。将InvokeMber结果强制转换为方法调用实际返回的类型。您可以尝试以下操作:
ConstructorInfo constructor = Type.GetType("class", true).GetConstructor(Type.EmptyTypes);
object classObject = constructor.Invoke(new object[]{});
MethodInfo methodInfo = Type.GetType("class", true).GetMethod("GetAll");
object returnValue = methodInfo.Invoke(classObject , new object[] { });
我还没有编译它,但它应该可以工作。您可以尝试以下方法:
ConstructorInfo constructor = Type.GetType("class", true).GetConstructor(Type.EmptyTypes);
object classObject = constructor.Invoke(new object[]{});
MethodInfo methodInfo = Type.GetType("class", true).GetMethod("GetAll");
object returnValue = methodInfo.Invoke(classObject , new object[] { });
我还没有编译它,但它应该可以工作。我不确定您是否对返回值或返回类型感兴趣。 下面的代码回答了这两个问题,我尝试执行sum方法并获取返回值的值和类型:
class Program
{
static void Main(string[] args)
{
var svc = Activator.CreateInstance(typeof(Util));
Object ret = typeof(Util).InvokeMember("sum", BindingFlags.InvokeMethod, Type.DefaultBinder, svc, new Object[] { 1, 2 });
Type t = ret.GetType();
Console.WriteLine("Return Value: " + ret);
Console.WriteLine("Return Type: " + t);
}
}
class Util
{
public int sum(int a, int b)
{
return a + b;
}
}
我不确定您是否对返回值或返回类型感兴趣。 下面的代码回答了这两个问题,我尝试执行sum方法并获取返回值的值和类型:
class Program
{
static void Main(string[] args)
{
var svc = Activator.CreateInstance(typeof(Util));
Object ret = typeof(Util).InvokeMember("sum", BindingFlags.InvokeMethod, Type.DefaultBinder, svc, new Object[] { 1, 2 });
Type t = ret.GetType();
Console.WriteLine("Return Value: " + ret);
Console.WriteLine("Return Type: " + t);
}
}
class Util
{
public int sum(int a, int b)
{
return a + b;
}
}