问题描述
我是全新的,这是我的第一个问题。抱歉我的格式。 下面代码调用MyMethod()时,参数需要用双引号引起来,是不是有什么原因?
当我尝试在没有引号的情况下运行它时出现错误 CS0103,但我不明白为什么仅变量名称是不够的。
谢谢
static void MyMethod(string child1 = "Liam",string child2 = "Jenny",string child3 = "John")
{
Console.WriteLine(child3);
}
static void Main(string[] args)
{
MyMethod("child3");
}
解决方法
child3
变量在 MyMethod
方法中定义,因此它仅在该上下文中可用。您不能在 child3
方法之外访问 MyMethod
变量。 Main
方法对名为 child3
的变量一无所知。
如果您想将数据传递给 MyMethod
方法,您有两个选择:
选项 #1:文字字符串
这就是你今天要做的:传递一个文字字符串。
static void Main(string[] args)
{
MyMethod("Hello,World!");
}
选项 #2:变量
正如我上面所说的,Main
方法无法访问 MyMethod
方法中定义的变量,例如 child3
。所以我们在 Main
方法中声明了一个新变量。此变量保存文本 Hello,World!
,然后将其传递给 MyMethod
方法。
static void Main(string[] args)
{
string myVariable = "Hello,World!";
MyMethod(myVariable);
}
在这两个示例中,文本 Hello,World!
将传递给 MyMethod
方法,该方法在 child1
变量中可用。所以 MyMethod
将处理三个变量值:
-
child1
:Hello,World!
(因为我们从Main
方法传递这个值) -
child2
:Jenny
(因为我们没有传递第二个参数,所以使用默认值) -
child3
:John
(因为我们没有传递第三个参数,所以使用默认值)
在 C# 中,文字字符串总是用双引号括起来,以便编译器知道它是文字字符串而不是变量名。因此,如果从传递给 MyMethod 的字符串中删除引号,编译器会感到困惑,因为它找不到名为 child3 的变量。 当编译器看到“child3”时,它会将它解释为一个字符串,但是当它看到 child3 时,它会将它解释为一个名为“child3”的变量,它可以包含任何字符串。
,您的程序没有将 John 打印到控制台,因为它“在您编写 MyMethod("child3")
时按照您的指令打印 child3” - 这不是打印 child3 参数内容的指令。
它打印出“John”,因为它总是打印 child3
并且 child3
的默认值是“John”,如果您不为其提供不同的值
把这个:
static void MyMethod(string child1 = "Liam",string child2 = "Jenny",string child3 = "John")
{
Console.WriteLine("value of child1 argument:" + child1);
Console.WriteLine("value of child2 argument:" + child2);
Console.WriteLine("value of child3 argument:" + child3);
}
然后尝试将其中一些放在您的主要内容中:
MyMethod();
MyMethod("child3");
MyMethod("a");
MyMethod("a","b");
MyMethod("a","b","c");
MyMethod(child3: "d");
MyMethod(child2: "d");
MyMethod(child3: "e",child2: "f");
你会看到发生了什么