将数组的值分配给一行中的单独变量 [英] 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
返回字符串嘿"和现在"的事实是任意的.实际上,它可以返回任何两个值,它们甚至不必是字符串.
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屋!