将数组的值分配给一行中的分隔变量 [英] Assign values of array to separate variables in one line
问题描述
我可以在 C# 中将数组中的每个值分配给一行中的单独变量吗?这是我想要的 Ruby 代码示例:
Can I assign each value in an array to separate variables in one line in C#? Here's an example in Ruby code of what I want:
irb(main):001:0> str1, str2 = ["hey", "now"]
=> ["hey", "now"]
irb(main):002:0> str1
=> "hey"
irb(main):003:0> str2
=> "now"
我不确定在 C# 中是否可以实现我想要的.
I'm not sure if what I'm wanting is possible in C#.
对于那些建议我只将字符串hey"和now"分配给变量的人来说,这不是我想要的.想象一下:
for those suggesting I just assign the strings "hey" and "now" to variables, that's not what I want. Imagine the following:
irb(main):004:0> val1, val2 = get_two_values()
=> ["hey", "now"]
irb(main):005:0> val1
=> "hey"
irb(main):006:0> val2
=> "now"
现在,方法 get_two_values
返回字符串hey"和now"的事实是任意的.实际上它可以返回任意两个值,它们甚至不必是字符串.
Now the fact that the method get_two_values
returned strings "hey" and "now" is arbitrary. In fact it could return any two values, they don't even have to be strings.
推荐答案
这在 C# 中是不可能的.
This is not possible in C#.
我能想到的最接近的事情是在索引的同一行中使用初始化
The closest thing I can think of is to use initialization in the same line with indexs
strArr = new string[]{"foo","bar"};
string str1 = strArr[0], str2 = strArr[1];
这篇关于将数组的值分配给一行中的分隔变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!