如何获取对象类型并将其传递给ObjectContent

时间:2014-12-10 18:24:39

标签: c#

我决定创建一个函数来将多行代码封装成一行代码。因此这个示例脚本。我无法工作的是获取课程Type并将其传递给ObjectContent的参数,以使其发挥作用。

在传递的参数对象上,使用xmlObjectType查看ObjectContent<xmlObjectType>(....)中的System.Type变量和xmlObjectType GetType()的{​​{1}}作业。你们做了什么来获得实际的对象类型以使用ObjectContent

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

       httpResponseMsg.StatusCode = HttpStatusCode.BadRequest;
       httpResponseMsg.Content = new ObjectContent<xmlObjectType>(parmXmlErrorLayout, new XmlMediaTypeFormatter());
   }
}

//Acutual scripts...
XmlBuilderTools xmlBuilderTools = new XmlBuilderTools();
XmlError xmlError = new XmlError();

xmlError.Message = "Foo";

return xmlBuilderTools.ErrorResponse(xmlError);

Edited - 找到解决此问题的方法。您不必调用它,而是使用其他有效的对象重载。我啊!

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

1 个答案:

答案 0 :(得分:0)

你根本无法做到这一点。你必须使用反射。

MethodInfo method = yourInstance.GetType().GetMethod("ObjectContent").MakeGenericMethod(new Type[] { xmlObjectType });
method.Invoke(this, new object[] { parmXmlErrorLayout, new XmlMediaTypeFormatter() });

否则也将类型作为参数传递给方法。