在C#中一次分配多个变量 [英] Assigning multiple variables at once in c#
问题描述
我想在c#中一次分配多个变量.我知道我可以将每个变量分配给数组的索引,但是我想知道是否还有另一种选择.我正在处理的示例代码如下:
I want to assign multiple variables at once in c#. I know I can assign each variable to the index of an array but am wondering if there is another alternative. The sample code I am working on is as follows:
我正在使用以下代码查找具有变量的行并返回该行:
I am using the following code to find the line with variables and return that line:
static public string linqalternative(string textfind1)
{
var nextLine = File.ReadLines(FILENAME)
.SkipWhile(line => !line.Contains(textfind1))
.Skip(1)
.First();
string linqalternative = nextLine;
return linqalternative;
}
然后,我在主子例程中调用上述函数,如下所示:该行具有多个值,并将其存储在数组中.然后,我想给新变量分配该数组的值.
Then I am calling the above function in the main subroutine as follows: The line has multiple values and it is stored in an array. Then I want new variables to be assigned the values of that array.
// Read Card C4
string stringC4 = linqalternative("C4 ISLTMT ISSSMMT");
string[] C4values =
stringC4.Split((string[])null, StringSplitOptions.RemoveEmptyEntries);
int ISLTMT = int.Parse(C4values[0]);
int ISSSMMT = int.Parse(C4values[1]);
int ISLTMTS = int.Parse(C4values[2]);
int ISIA = int.Parse(C4values[3]);
float RPIA = float.Parse(C4values[4]);
float RSQMIA = float.Parse(C4values[5]);
int ITRMIA = int.Parse(C4values[6]);
int ISAVEC = int.Parse(C4values[7]);
我可以将上面显示的所有变量分配为一行还是两行,或者这是唯一的选择?
Can I assign all the variables shown above in a line or two or that is the only alternative ?
推荐答案
要回答您的问题,可以使用基本变量声明语法对相同类型的变量执行此操作:
To answer your question, yes it is possible to do so for variables of the same type, using basic variable declaration syntax:
int ISLTMT = int.Parse(C4values[0]), ISSSMMT = int.Parse(C4values[1]); // etc., etc.
float RPIA = float.Parse(C4values[4]), RSQMIA = float.Parse(C4values[5]);
但是,这不是很容易理解,也不是推荐的做法,尤其是包含尝试分配的变量.
However, this is not very readable and it is not a recommended practice, especially for as many variables as you are trying to assign.
就像@meda在评论中说的那样,不要太拘谨了,它的自由性和清晰度更好."
As @meda said in the comments, "dont be stingy with the lines, its free and better for clarity".
这篇关于在C#中一次分配多个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!