新年快乐!
我从OPC UA服务器收集了数据,数据如下:
0;0;0;0;0;我需要将这些数据写入OPC UA服务器,好的语法需要:
UInt16[] temp = { 0, 0, 0, 0, 0 };如何转换第一个具有Uint16数组的字符串?
发布于 2022-01-05 17:28:07
使用linq:
var dataString = "0;0;0;0;0;";
var temp = dataString.Split(';')
.Where(s => !s.Equals(string.Empty))
.Select(value => Convert.ToUInt16(value))
.ToArray();

发布于 2022-01-05 17:29:54
在使用String.Split()方法拆分字符串之后,您可以在try-catch块中使用Convert.ToUInt16()方法来安全地将String数据转换为UInt16类型。开发的静态方法如下:
public static UInt16[] Convert(String[] values)
{
UInt16[] numbers = new UInt16[values.Length - 1];
try
{
for(int i = 0 ; i < values.Length - 1 ; ++i)
numbers[i] = System.Convert.ToUInt16(values[i]);
}
catch(FormatException){}
return numbers;
}
public static void Print(UInt16[] numbers)
{
for(int index = 0 ; index < numbers.Length ; ++index)
System.Console.WriteLine("[{0}]: {1}", index, numbers[index]);
}下面是调用静态方法的应用程序:
String[] values= "1;2;3;4;5;".Split( ';' );
uint size = (uint)values.Length - 1;
UInt16[] numbers = new UInt16[size];
numbers = Convert(values);
Print(numbers);该程序产生以下输出:
[0]: 1
[1]: 2
[2]: 3
[3]: 4
[4]: 5发布于 2022-01-05 17:36:26
谢谢大家,它终于开始运作了:
string data = childNode.InnerXml; //0;0;0;0;0;
string[] words = data.Split(';').SkipLast(1).ToArray(); //need to remove the last empty element of the array
UInt16[] myInts = Array.ConvertAll(words, s => UInt16.Parse(s));https://stackoverflow.com/questions/70596979
复制相似问题