尝试在同一个类中使用Reflection来调用Method

时间:2010-07-08 04:26:25

标签: c# wcf reflection

我有一个WCF服务,它接受一个对象作为具有URI和方法名称的参数。 我想要做的是有一个方法,看看@的URI,如果它包含单词“localhost”,它将使用反射并调用一个方法,该方法作为参数传入,在同一个类中,返回一个值并继续。

public class Test
{
     public GetStatResponse GetStat(GetStatRequest request)
     {

        GetStatResponse returnValue = new GetStatResponse();

         if(Helpers.Contains(request.ServiceURI,"localhost", StringComparison.OrdinalIgnoreCase))
         {
             MethodInfo mi = this.GetType().GetMethod(request.ServiceMethod /*, BindingFlags.Public | BindingFlags.IgnoreCase*/);
             returnValue = (GetStatResponse)mi.Invoke(this,null);
         }

以上是与此问题相关的代码段。我没有解决MethodInfo问题,但我遇到了关于mi.Invoke的问题。我收到的例外情况是“调用的目标引发了异常。”内部异常“对象引用未设置为对象的实例”。我已经尝试将代码更改为(GetStatResponse)mi.Invoke(new Test(),null),没有运气。作为班级考试。

我对其他如何解决这个问题的建议持开放态度,我只是认为反思可能是最简单的。

我通过测试调用的方法定义为

public GetStatResponse TestMethod() 
{
         GetStatResponse returnValue = new GetStatResponse(); 
         Stat stat = new Stat();
         Stat.Label = "This is my label";
         Stat.ToolTip = "This is my tooltip";
         Stat.Value = "this is my value"; 

         returnValue.Stat = stat;
         return returnValue;
}

2 个答案:

答案 0 :(得分:0)

在调用方法之前,您可能需要确保通过反射的MethodInfo不是空的:

MethodInfo mi = this.GetType().GetMethod(
    request.ServiceMethod, 
    BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase
);

// Make sure that the method exists before trying to call it
if (mi != null)
{
    returnValue = (GetStatResponse)mi.Invoke(this, null);
}

更新后,似乎在您调用的方法中抛出异常:

GetStatResponse returnValue = new GetStatResponse(); 
// Don't forget to initialize returnValue.Stat before using it:
returnValue.Stat = new WhateverTheTypeIs();
returnValue.Stat.Label = "This is my label";

答案 1 :(得分:0)

因为您没有在GetMethod()调用中指定BindingFlags,所以只返回与包含PUBLIC的request.ServiceMethod的名称匹配的方法。

检查您尝试调用的方法是否为public,否则MethodInfo将返回null。

如果它不公开,则将方法设为公开或包含BindingFlags.NonPublic标志。

此外,在调用mi.Invoke

之前,您应该始终确保mi!= null
相关问题