Невозможно вернуть значение по умолчанию словаря в веб-API - PullRequest
0 голосов
/ 17 апреля 2020

В моем WEB API я пытаюсь вернуть значение по умолчанию для моей словарной переменной, чтобы я мог обработать любое исключение / ошибку.

Dictionary<string, string> dict = new Dictionary<string, string>();
        var error = "06";
        string key = "default";
        try
        {
            var serialPort = new SerialPort("COM2", 9600, Parity.Even, 8, StopBits.One);
            //serial port settings and opening it
            serialPort.Open();

            var stream = new SerialStream(serialPort);
            stream.ReadTimeout = 2000;
            // send request and waiting for response
            // the request needs: slaveId, dataAddress, registerCount            
            var responseBytes = stream.RequestFunc3(slaveId, dataAddress, registerCount);

            // extract the content part (the most important in the response)
            var data = responseBytes.ToResponseFunc3().Data;

            var finalData = floatArray(data);


            //var result = data.Where(r => r > 0).Select(r => r.ToString()).ToArray();
             dict = finalData.Select((b, i) => (value: b, index: i)) // convert bytes to sequence of (byte value, index)
                                .ToDictionary(x => x.index.ToString(), x => x.value.ToString());

            serialPort.Close();

            return dict;
        }
        catch (Exception ex)
        {
            return dict.TryGetValue(key, out error);
        }

Я использую клиент для отправки сообщения об ошибке, чтобы что я могу проверить свои try..catch. Но я не могу установить значение по умолчанию для моей dict переменной, так как получаю ошибку ниже

Невозможно неявно преобразовать тип 'bool' в 'System.Collections.Generi c .Dictionary'

Как мне этого добиться? Любая помощь будет принята с благодарностью.

1 Ответ

1 голос
/ 17 апреля 2020

TryGetValue : Получите Value на Key и верните bool, вы можете изменить catch, как следующий код:

try
{
...
}
catch (Exception ex)
{
    dict.Add(key, error);
    return dict;
}

Надеюсь, это поможет.

...