gpt4 book ai didi

c# - 将对象 [,] 转换为字符串 [,]

转载 作者:太空狗 更新时间:2023-10-30 00:39:25 24 4
gpt4 key购买 nike

我正在尝试将 object[,] 数组(例如其中包含一些整数) 转换为 string[,]大批。我写了这段代码,但 Visual Studio 给我一个错误提示:

Cannot implicitly convert String[] to String[,].

我应该给 Array.ConvertAll 函数什么参数?非常感谢。

object[,] input = GetSelectedRange();

string[,] dst = Array.ConvertAll<object[,], string[,]>(
input,
x => x.ToString()
);

最佳答案

如果您的项目是 object[][] 而不是 object[,] 会容易得多。但是对于object[,],为什么不用传统的方法呢?

object[,] input = GetSelectedRange();
string[,] output = new string[input.GetLength(0), input.GetLength(1)];
for (int i = 0; i < input.GetLength(0); ++i)
for (int j = 0; j < input.GetLength(1); ++j)
output[i, j] = input[i, j]?.ToString(); //give additional ?. to check if your input is null

Olivier 的建议: 使用 C#6 语法检查输入是否为空 ?.

或者,如果您使用较低版本,请使用三元运算符:

object[,] input = GetSelectedRange();
string[,] output = new string[input.GetLength(0), input.GetLength(1)];
for (int i = 0; i < input.GetLength(0); ++i)
for (int j = 0; j < input.GetLength(1); ++j)
output[i, j] = input[i, j] == null ? null input[i, j].ToString();

关于c# - 将对象 [,] 转换为字符串 [,],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35673108/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com