Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在C中使用占位符时输出错误#_C#_.net_Output_Console.writeline - Fatal编程技术网

C# 在C中使用占位符时输出错误#

C# 在C中使用占位符时输出错误#,c#,.net,output,console.writeline,C#,.net,Output,Console.writeline,当我在C#中使用{0}占位符时,我得到了错误的输出。就是这样,但下面是一个代码块,请看下面我的评论: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace Ch06Ex03 {

当我在C#中使用{0}占位符时,我得到了错误的输出。就是这样,但下面是一个代码块,请看下面我的评论:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using static System.Console;
    namespace Ch06Ex03
    {
        class Program
        {
            static void Main(string[] args)
            {
                int argument = 10;//test argument
                WriteLine($"The argument is={argument}");
                *WriteLine($"The argument is={0}",argument);*/*Here,When I use the {0},output is 0,Why not is 10?*/
                ReadKey();
            }
        }
    }

字符串前的美元符号指示编译器执行插值,从某种意义上讲,将括号之间的部分解释为代码。删除美元符号以执行常规格式操作


您正在混合插值字符串和复合格式。 有关更多信息,请参阅

插值字符串

Console.WriteLine($"Key: {value}");
$表示我们正在使用插值字符串

复合格式

Console.WriteLine("Key: {0}", value);
复合格式仅在特定的方法中可用,如
Console.WriteLine
String.format
。。。在这些方法中,“0”表示以下参数中的索引。

首先,删除它(它甚至不会在我的VS2012上编译):

using static System.Console;
然后,使用以下命令:

int argument = 10;//test argument
 Console.WriteLine(String.Format("The argument is={0}", argument));
 Console.ReadKey();

通常,使用类限定方法是更好的做法。如果两个类包含相同的方法名称,则可以明确目的,并防止出现不明确的引用编译错误。

此版本工作正常。问题是您的版本中第二种情况下的美元符号

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;

 namespace ConsoleApplication1
 {
    class Program
    {
       static void Main(string[] args)
       {
        int argument = 10;//test argument
        Console.WriteLine($"The argument is={argument}");
        Console.WriteLine("The argument is={0}", argument);
        Console.WriteLine(String.Format("The argument is = {0}", argument));//Otra forma        
        Console.ReadKey();
    }
}

}

因为
$
前缀意味着
{0}
变为
0
。避免使用插值字符串作为格式说明符。如果需要,必须将
{}
加倍以转义。这是用户错误,谢谢您的回答谢谢您的回答。