无法 return Web 中字典的默认值 api
Unable to return the default value of dictionary in web api
在我的 WEB API
中,我正在尝试 return 我的字典变量的默认值,以便我可以处理任何 exception/error.
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
变量设置默认值,因为我遇到的错误
Cannot implicitly convert type 'bool' to 'System.Collections.Generic.Dictionary'
如何实现?任何帮助将不胜感激。
TryGetValue : 通过 Key
和 return 得到 Value
一个 bool
,你可以改变 catch
,像下面的代码:
try
{
...
}
catch (Exception ex)
{
dict.Add(key, error);
return dict;
}
希望对您有所帮助。
在我的 WEB API
中,我正在尝试 return 我的字典变量的默认值,以便我可以处理任何 exception/error.
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
变量设置默认值,因为我遇到的错误
Cannot implicitly convert type 'bool' to 'System.Collections.Generic.Dictionary'
如何实现?任何帮助将不胜感激。
TryGetValue : 通过 Key
和 return 得到 Value
一个 bool
,你可以改变 catch
,像下面的代码:
try
{
...
}
catch (Exception ex)
{
dict.Add(key, error);
return dict;
}
希望对您有所帮助。