【问题标题】:C# syntax ignoring a parameter, asking of possibilitiesC# 语法忽略参数,询问可能性
【发布时间】:2014-04-19 08:39:33
【问题描述】:

public static void Search(string name, int age = 21, string city = "Tehran")
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age, city));
}

我想调用 Search 方法,使用 name 和 city 参数来保持 age 的默认值。

AFAIK 参数应按名称引用

Search("Mahdi", city: "Mashhad");

我想知道是否可以在不指定年龄值且不按名称呼叫城市的情况下拨打电话?我的意思是跳过一个参数,比如:

Search("Mahdi",,"Mashhad");

我看到for 循环的行为几乎相似

for (int i = 0; ; i++) { some code; }

或任何其他匹配大小写的语法?

【问题讨论】:

  • 不,这是不可能的。 for 循环不接受任何参数 - 这种行为不相似

标签: c# syntax parameters optional-parameters named-parameters


【解决方案1】:

改成

public static void Search(string name, string city = "Tehran", int age = 21)
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age, city));
}

现在你可以把它当作

Search("Mahdi", "Mashhad");

可选参数定义在参数列表的末尾, 在任何必需的参数之后。 http://msdn.microsoft.com/en-us/library/dd264739.aspx

【讨论】:

  • 不,我的意思是理性的想法 :) 有这个意思的争论。在所有答案中,这个更合乎逻辑,代码更少,一切都在它的位置。谢谢。
  • @MahdiTahsildari 我只是因为我的英语能力而误解了它,我很高兴能帮助你。
【解决方案2】:

您可以为 age 使用可为空的 int。像这样:

public static void Search(string name, int? age = null, string city = null)
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age ?? 21, city ?? "Tehran"));
}

那么你可以调用以下组合:

Search("Mahdi");
Search("Mahdi", 20);
Search("Mahdi", null, "Cairo");

这将使用age=21city="Tehran" 作为默认值。

【讨论】:

  • 看起来不错,但如果我们这样做,那么可选参数的意义何在?
  • 如果所有参数都是非可选的,则必须始终提供所有三个参数。喜欢:Search("Mahdi", null, null );
【解决方案3】:

只需创建一个overload,它接受两个字符串参数,如下所示:

public static void Search(string name, string city)
{
    Search(name, 21, city);
}

public static void Search(string name, int age = 21, string city = "Tehran")
{
    MessageBox.Show(String.Format("Name = {0} - Age = {1} - City = {2}", 
        name, age, city));
}

然后这样称呼它:

Search("Mahdi", "Mashhad");

【讨论】:

  • 你可以调用Search(name, city: city)而不是复制默认值
  • @SergeyBerezovskiy 我考虑过,但除非您也更改参数名称,否则将导致无限递归。
  • @p.s.w.g 我认为编译器足够聪明,可以捕捉到这一点,它根本不会进入递归。
  • @MahdiTahsildari 好吧,我在第一个重载中使用Search(name, city: city) 测试了这段代码,是的,它确实导致了递归。但是,如果您在第一次重载中更改 city 参数的名称,则它可以正常工作。
  • @p.s.w.g 是的,你是对的 - 我没有注意到这里的自我调用
猜你喜欢
  • 2019-02-16
  • 1970-01-01
  • 2015-05-13
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-24
  • 1970-01-01
  • 2016-05-19
相关资源
最近更新 更多