【问题标题】:C# - When you have multiple parameters with default values, why are double quotes needed [closed]C# - 当您有多个具有默认值的参数时,为什么需要双引号 [关闭]
【发布时间】:2021-05-26 07:29:52
【问题描述】:

我是全新的,这是我的第一个问题。对不起我的格式。 下面的代码中调用 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 变量在哪里?您当前正在传递一个文字字符串
  • 可能有助于参考您从示例中获取的站点,以提供有关您要实现的目标的更多上下文 - w3schools.com/cs/cs_method_parameters.asp
  • 是的,那是个好主意。我会记住未来。

标签: c# parameters default-value


【解决方案1】:

child3 变量在MyMethod 方法中定义,因此它仅在该上下文中可用。您不能在MyMethod 方法之外访问child3 变量。 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(因为我们没有传递第三个参数,所以使用默认值)

【讨论】:

  • 您有选项 3:MyMethod(myVariable + "Hello, World!");
【解决方案2】:

在 C# 中,文字字符串总是用双引号引起来,以便编译器知道它是文字字符串而不是变量名。因此,如果从传递给 MyMethod 的字符串中删除引号,编译器会感到困惑,因为它找不到名为 child3 的变量。 当编译器看到“child3”时,它会将其解释为一个字符串,但是当它看到 child3 时,它会将其解释为一个名为“child3”的变量,它可以包含任何字符串。

【讨论】:

    【解决方案3】:

    您的程序没有将 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");
    

    你会看到发生了什么

    【讨论】:

      猜你喜欢
      • 2014-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-18
      • 1970-01-01
      • 1970-01-01
      • 2015-12-29
      • 1970-01-01
      相关资源
      最近更新 更多