用户定义的转换错误

时间:2013-02-06 11:12:43

标签: c# .net casting

我的解决方案中有2个项目,web-service项目和win-forms项目。我想将web-service的返回数据转换为win-forms数据。我在两个项目中都定义了终端类。在win应用程序中,我写了这个演员:

static public implicit operator List<Terminal>(EService.Terminal[] svcTerminals)
{
    List<Terminal> terminals = new List<Terminal>();
    foreach (var svcTerminal in svcTerminals)
    {
        Terminal terminal = new Terminal();
        terminal.TerminalID = svcTerminal.TerminalID;
        terminal.TerminalTypeID = svcTerminal.TerminalTypeID;
        terminal.TerminalGUID = svcTerminal.TerminalGUID;
        terminal.Description = svcTerminal.Description;
        terminal.Name = svcTerminal.Name;
        terminal.PortID = svcTerminal.PortID;
        terminals.Add(terminal);
    }

    return terminals;
}

但它不起作用并且提供错误用户定义的转换必须转换为封闭类型,这适用于 List 强制转换。但是在终端中,一切都很好

static public implicit operator Terminal(EService.Terminal svcTerminal)
{
    Terminal terminal = new Terminal();
    terminal.TerminalID = svcTerminal.TerminalID;
    terminal.TerminalTypeID = svcTerminal.TerminalTypeID;
    terminal.TerminalGUID = svcTerminal.TerminalGUID;
    terminal.Description = svcTerminal.Description;
    terminal.Name = svcTerminal.Name;
    terminal.PortID = svcTerminal.PortID;
    return terminal;
}

任何人都可以帮我解决这个问题,以便

return (List<Terminal>)eService.CheckTerminal(guid, ref cityName, ref portName);

而不是

List<Terminal> terminals = new List<Terminal>();
var svcTerminals = eService.CheckTerminal(guid, ref cityName, ref portName);
foreach (var svcTerminal in svcTerminals)
{
    Terminal terminal = new Terminal();
    terminal.TerminalID = svcTerminal.TerminalID;
    terminal.TerminalTypeID = svcTerminal.TerminalTypeID;
    terminal.TerminalGUID = svcTerminal.TerminalGUID;
    terminal.Description = svcTerminal.Description;
    terminal.Name = svcTerminal.Name;
    terminal.PortID = svcTerminal.PortID;
    terminals.Add((Terminal)svcTerminal);
}
return terminals;

2 个答案:

答案 0 :(得分:4)

你可以这样做:

eService.CheckTerminal(guid, ref cityName, ref portName).Select(x => (Terminal) x);

答案 1 :(得分:0)

MSDN说

  

要转换的参数类型或转换结果的类型(但不是两者)都必须是包含类型。

因此,要使他工作,您需要将转换运算符声明移动到要转换为(或来自)的类,即List<Terminal>EService.Terminal[]。由于您无法将方法添加到标准类中,我建议使用此方法而不是运算符,或使用LINQ。