因为C#格式化而混淆 [英] Confuse because of formattingin C#
问题描述
我基本上是从C ++开始使用C#,我觉得格式混乱。
I basically started from C++ now in C#,I find formatting confusing.
Console.WriteLine("Number of command line parameters = {0}",
args.Length);
在上面的代码{0}中,这打印出命令行args数组的长度。
但这项工作有所不同使用{1},请参阅以下代码。
In above code {0} has been used,this prints out the length of command line args array.
But this work differenetly with {1},see following code.
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
以上代码的
输出为:
命令行参数数量= 5
Arg [0] = [abc]
Arg [1] = [def]
Arg [2] = [ghi]
Arg [3] = [klm]
Arg [4] = [nop]
我想知道的是{0}如何打印索引但{1}打印存储在相关索引中的值。
output of above code is:
Number of command line parameters = 5
Arg[0] = [abc]
Arg[1] = [def]
Arg[2] = [ghi]
Arg[3] = [klm]
Arg[4] = [nop]
What I want to know is how {0} prints indexes but {1} prints values stored in relevent indexes.
推荐答案
因为{和}内的数字格式字符串中的索引是以下参数的索引:
Because the number inside the { and } within the format string is the index to the following parameters:
Console.WriteLine("{0}:{1}:{2}", a, b, c);
^ ^ ^
| | -- parameter 2: 'c'
| ------ parameter 1: 'b'
---------- parameter 0: 'a'
这是一种将参数与结果中的位置联系起来的方法字符串 - 它们不必按数字顺序排列,甚至不一样!
It's a way of tieing parameters to positions within the resulting string - they don't have to be in numerical order, or even different!
Console.WriteLine("{1}:{0}:{2}", a, b, c);
Console.WriteLine("{0}:{1}:{0}", a, b)
;
问题:我想要什么要知道{0}如何打印索引,但{1}打印存储在相关索引中的值。?
答:因为索引o指的是循环控制变量i,所以它远离打印循环计数,如0,1,2,3,4..etc。,
索引1指的是args [i]表示 - > args [0],args [1],args [2]等,因为args [i]包含命令行参数值,所以它打印abc,def ...等,
Question : What I want to know is how {0} prints indexes but {1} prints values stored in relevent indexes.?
Answer: Because index o refers to loop control variable i, so it aways print loop count like 0,1,2,3,4..etc.,
index 1 refers to the args[i] means -> args[0],args[1],args[2] etc., as args[i] contains command line argument value ,so it prints abc , def ...etc.,
这篇关于因为C#格式化而混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!