今天在做C#练习时,遇到了一个奇怪的现象。
这个代码最开始只是想学一下函数的应用,我就编了这么一个代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionPractice_1
{
class Program
{
static void Main(string[] args)
{
int[] MyArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
int MaxValue = SearchMaxValue(MyArray);
Console.Write("The max value in array: { ");
foreach (int Number in MyArray)
{
Console.Write("{0} ", Number);
}
Console.WriteLine("}\nis: {0}", MaxValue);
Console.ReadKey();
}
static int SearchMaxValue(int[] intArray)
{
int maxValue = intArray[0];
for (int i = 0; i < intArray.Length; i++)
{
if (intArray[i] > maxValue)
{
maxValue = intArray[i];
}
}
return maxValue;
}
}
}
结果……
……这就尴尬了
去问了问别人,就把第20行改成了:
Console.WriteLine("}" + "is: {0}", MaxValue);
还是不行,想试着用转义字符 '\}'(乱用的),结果直接报错。
最后只能分行写了
Console.WriteLine("}");
Console.WriteLine("is: {0}", MaxValue);
这才解决了问题。
果然还是得会用调试器才好啊……
但我还是做了一些实验,比如我写了下面一个Console.WriteLine() 的一行代码:
Console.WriteLine("}{");
这样是可以的,也就是我这次做的函数的练习的错误并不在 '}' 不能与 '{' 共用
但是如果是下面这一行的话:
Console.WriteLine("}{0}", 1);
这就出问题了,也就是说,'}' 不能与 {index[,alignment][:formatString]} 一起用。
于是我以为只能分行写,在写我的第一篇blog(就是这篇啦~)时,想看看 {} 的使用格式,看到了这篇 blog:
http://www.cnblogs.com/fsjohnhuang/articles/2451964.html(没有想打广告QAQ,只是想写一下我得知这一点的来源,要是原主看见,侵权了,我会删的)然后,才发现,我的转义字符用错了
在Console.WriteLine() 里,‘{’ 的转义字符是 ‘{{’,而‘}’ 的转义字符是 ‘}}’
好吧,搞了半天,居然是转义字符用错了
所以,最后的结论是
在Console.WriteLine() 中,如果 '}' 要与{index[,alignment][:formatString]} 一起用,'}' 必须使用转义字符 ‘}}’
其实写下这篇blog,也是希望像我一样的新手,遇到这种问题是,能够不会像我一样纠结了这么久,希望我的这篇blog能给他们带来帮助。
最后,是我最终的代码,望大家指教
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionPractice_1
{
class Program
{
static void Main(string[] args)
{
int[] MyArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 };
int MaxValue = SearchMaxValue(MyArray);
Console.Write("The max value in array: { ");
foreach (int Number in MyArray)
{
Console.Write("{0} ", Number);
}
Console.WriteLine("}}\n" + "is: {0}", MaxValue);
Console.ReadKey();
}
static int SearchMaxValue(int[] intArray)
{
int maxValue = intArray[0];
for (int i = 0; i < intArray.Length; i++)
{
if (intArray[i] > maxValue)
{
maxValue = intArray[i];
}
}
return maxValue;
}
}
}
希望大家喜欢这片blog。