在静态函数中调用ObjectContent结果"对象引用未设置为对象的实例"错误

时间:2014-12-10 21:32:14

标签: c# nullreferenceexception

来自How do I get object type and passed it on to ObjectContent的已接受答案的新鲜内容,即将class类型传递给新创建的函数,其中包含ObjectContent个对象。

我的下一步是将其转换为静态类/函数。我尽我所能在将type.GetMethod("ObjectContent", ...)分配给methodInfo变量时收到异常错误。

错误消息是"对象引用未设置为对象的实例"。

type.GetMethod("ObjectContent", ...)这里的问题似乎是什么?这个问题的解决方法是什么?

public class XmlError
{
    public string Message { get; set; }
}
public static class XmlBuilderTools 
{
    public static HttpResponseMessage ErrorResponse(object parmXmlErrorLayout)
    {
        HttpResponseMessage httpResponseMsg = new HttpResponseMessage();
        Type type = parmXmlErrorLayout.GetType();  //typeof(parmXmlErrorLayout);

        System.Reflection.MethodInfo methodInfo = type.GetMethod("ObjectContent", (System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.FlattenHierarchy));
        returnHttpResponseMessage.Content = (HttpContent)methodInfo.Invoke(null, new object[] { parmXmlErrorLayout, new XmlMediaTypeFormatter() });

        httpResponseMsg.StatusCode = HttpStatusCode.BadRequest;
    }
}

public class Foo()
{
   public HttpResponseMessage FooFoo()
   {
       //Acutual scripts...
       XmlError xmlError = new XmlError();

       xmlError.Message = "Foo";

       return XmlBuilderTools.ErrorResponse(xmlError);
   }
}

最初这适用于非静态类/对象

returnHttpResponseMessage.Content = new ObjectContent<XmlError>(xmlError, new CustomXmlFormatter());

1 个答案:

答案 0 :(得分:1)

你有

 Type type = parmXmlDataLayout.GetType();  //typeof(parmXmlDataLayout);

但你传入

object parmXmlErrorLayout

所以不应该

Type type = parmXmlErrorLayout.GetType();  //typeof(parmXmlErrorLayout);

如果没有,则需要定义parmXmlDataLayout的实例,因为我在代码中的任何地方都没有看到。因此,为什么你会从type.Gettype中得到错误,类型可能是null

Edited by fletchsod - Alternative workaround to the problem

而不是调用,显然还有另一个重载到ObjectContent,效果很好。我啊!我之前没有使用太多相同的对象。该问题的解决方案是

foo.Content = new ObjectContent(parmXmlErrorLayout.GetType(), parmXmlErrorLayout, new CustomXmlFormatter());