Assign values of array to separate variables in on

2019-01-19 10:52发布

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"

I'm not sure if what I'm wanting is possible in C#.

Edit: 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"

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.

8条回答
smile是对你的礼貌
2楼-- · 2019-01-19 11:04

You can do it in one line, but not as one statement.

For example:

int str1 = "hey"; int str2 = "now";

Python and ruby support the assignment you're trying to do; C# does not.

查看更多
Melony?
3楼-- · 2019-01-19 11:09

You can use named tuples with C# 7 now.

{
  (string part1, string part2) = Deconstruct(new string[]{"hey","now"});
}

public (string, string) Deconstruct(string[] parts)
{
   return (parts[0], parts[1]);
}
查看更多
该账号已被封号
4楼-- · 2019-01-19 11:10

The real-world use case for this is providing a convenient way to return multiple values from a function. So it is a Ruby function that returns a fixed number of values in the array, and the caller wants them in two separate variables. This is where the feature makes most sense:

first_name, last_name = get_info() // always returns an array of length 2

To express this in C# you would mark the two parameters with out in the method definition, and return void:

public static void GetInfo(out string firstName, out string lastName)
{
    // assign to firstName and lastName, instead of trying to return them.
}

And so to call it:

string firstName, lastName;
SomeClass.GetInfo(out firstName, out lastName);

It's not so nice. Hopefully some future version of C# will allow this:

var firstName, lastName = SomeClass.GetInfo();

To enable this, the GetInfo method would return a Tuple<string, string>. This would be a non-breaking change to the language as the current legal uses of var are very restrictive so there is no valid use yet for the above "multiple declaration" syntax.

查看更多
欢心
5楼-- · 2019-01-19 11:13

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];
查看更多
看我几分像从前
6楼-- · 2019-01-19 11:14

You can do this in C#

string str1 = "hey", str2 = "now";

or you can be fancy like this

        int x, y;
        int[] arr = new int[] { x = 1, y = 2 };
查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-19 11:16

I'm not sure if what I'm wanting is possible in C#.

It's not.

查看更多
登录 后发表回答