简体   繁体   中英

user-defined conversion error

I have 2 project in my solution, a web-service project and a win-forms project. I want to cast returning data of web-service to win-forms data. I have class Terminal defined in both projects. In the win app I have written this cast:

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;
}

but it does not work and gives the error user-defined conversion must convert to or from enclosing type , this happens for List cast. But in Terminal cast everything is ok

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;
}

Can anyone help me fix this so that I can

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

Instead of

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;

你可以做:

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

MSDN says

Either the type of the argument to be converted, or the type of the result of the conversion, but not both, must be the containing type.

So, for his to work you need to move your conversion operator declaration into the class you are converting to (or from), ie List<Terminal> or EService.Terminal[] . Since you can't add methods into a standard classes, I would recommend making this method rather than an operator, or using LINQ.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM