【问题标题】:In XML-RPC.NET how to handle a return value whose type is not known until runtime?在 XML-RPC.NET 中,如何处理直到运行时才知道类型的返回值?
【发布时间】:2012-09-19 15:50:09
【问题描述】:

我使用 C# 中的 XML-RPC.NET 库在我的服务器上调用 XML-RPC 方法。该方法在一切正常时返回一个字符串,但在发生错误时返回一个 XmlRpcStruct。

当我得到的返回类型与我在方法签名中指定的不同时,XML-RPC.NET 引发了异常:

string login(string username, string password);

异常消息:“响应包含预期字符串的结构值”

在 XML-RPC.NET 的文档中是这样说的:

“如何指定直到运行时才知道类型的数据?

有时直到运行时才知道参数、返回值或结构成员的类型。在这种情况下,应使用 System.Object 数据类型。对于返回值,实际类型可以在运行时确定并适当处理。”

所以我将返回类型更改为对象,现在它可以工作了。但是现在我不知道如何处理返回值。如果它是 XmlRpcStruct 类型,我不想将它转换为我的错误类。否则我把它当作一个字符串。如何将其转换为我的错误类? XML-RPC-NET 是否有转换方法或我可以调用的方法?

public interface Proxy : IXmlRpcProxy
{
    [XmlRpcMethod("login")]
    object login(string username, string password);
}

// When the login method fails I get an XmlRpcStruct that has a
// key "status" with a string value. I'd like to cast the returned
// XmlRpcStruct to my Error class. How?
public class Error : XmlRpcStruct
{
    public string status;
}

然后当我调用方法时:

object ret = proxy.login("admin", "1234");
Type t = ret.GetType();

if (t == typeof(XmlRpcStruct))
{
    // This will set err to null even though ret is not null
    // How do I convert it?
    Error err = ret as Error;
}
else
{
    string result = (string)ret;
}

有没有更简单的方法来做到这一点?我可以将我的方法设置为字符串的返回类型,然后尝试/捕获方法调用,但随后我丢失了错误中返回的状态消息。

【问题讨论】:

    标签: c# .net xml-rpc xml-rpc.net


    【解决方案1】:

    如果您的 Error 类包含一个 XmlRpcStruct 变量会怎样:

    public class Error
    {
        public string status;
        public XmlRpcStruct xmlstr;
    }
    

    然后您可以将您的 XmlRpcStruct 分配给 Error 对象的变量:

    object ret = proxy.login("admin", "1234");
    Type t = ret.GetType();
    
    if (t == typeof(XmlRpcStruct))
    {
        Error err = new Error();
        err.xmlstr = (XmlRpcStruct)ret;
    }
    else
    {
        string result = (string)ret;
    }
    

    而且您仍然可以通过 Error 类的变量访问原始 XmlRpcStruct,而不会将其丢失到 try 语句中。通过继承可能有更好的方法来实现这一点,但这是一个快速解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-09
      相关资源
      最近更新 更多