简体   繁体   English

将可选参数传递给方法

[英]Passing optional parameters to method

I am trying to pass optional parameter to method and having hard times understanding why it doesn't work.我正在尝试将可选参数传递给方法,并且很难理解为什么它不起作用。 As most popular answer here ( How can you use optional parameters in C#? ) says public void SomeMethod(int a, int b = 0) .正如这里最受欢迎的答案( How can you use optional parameters in C#? )说public void SomeMethod(int a, int b = 0) So I have tried the same below.所以我在下面尝试了同样的方法。

Can I get rid of else statement here?我可以在这里摆脱else声明吗? I mean can I use parameter that is otherwise ="" if not something else = optional?我的意思是如果不是其他=可选的,我可以使用否则=""的参数吗? If it exists, method will get it, if not then skip it?如果存在,方法将获取它,如果不存在则跳过它?

Here is code with else statement that works ( https://dotnetfiddle.net/sy5FW5 ):这是带有 else 语句的代码( https://dotnetfiddle.net/sy5FW5 ):

using System;

public class Program
{
    public static void Main()
    {

        int MyNumber = 6;
        string StringOne;
        string StringTwo;

        if (MyNumber != 5)
        {
            StringOne = "Number is not 5";
            StringTwo = "True that!";
        }
        else
        {
            StringOne = "";
            StringTwo = "";
        }
        CheckNumber(StringOne, StringTwo);
    }

    public static void CheckNumber(string StringOne, string StringTwo)
    {
        Console.WriteLine(StringOne + "\n" + StringTwo);
    }
}

Above code is what I need and it is working fine.上面的代码是我需要的,它工作正常。 My question is more like is there any better way?我的问题更像是有没有更好的方法?

Here is what I was thinking of, but it does not work:这是我的想法,但它不起作用:

using System;

public class Program
{
    public static void Main()
    {

        int MyNumber = 6;
        string StringOne;
        string StringTwo;

        if (MyNumber != 5)
        {
            StringOne = "Number is not 5";
            StringTwo = "True that!";
        }
        CheckNumber(StringOne, StringTwo);
    }

    public static void CheckNumber(string StringOne = "", string StringTwo = "")
    {
        Console.WriteLine(StringOne + "\n" + StringTwo);
    }
}

Variables are not assigned in: CheckNumber(StringOne, StringTwo);变量未分配在: CheckNumber(StringOne, StringTwo);

I was thinking that I can make parameters optional by using string StringOne = "" but it does not seem to be the solution?我在想我可以通过使用string StringOne = ""使参数成为可选参数,但这似乎不是解决方案?

In your particular case, you don't need to make the parameters of your method optional, you just need to initialize your variables to the default value you want to use:在您的特定情况下,您不需要将方法的参数设为可选,只需将变量初始化为您要使用的默认值:

    int MyNumber = 6;
    string StringOne = "";  // <--
    string StringTwo = "";  // <--

    if (MyNumber != 5)
    {
        StringOne = "Number is not 5";
        StringTwo = "True that!";
    }
    CheckNumber(StringOne, StringTwo);

A word of caution: Please do not take that as an invitation to go ahead and explicitly initialize all your variables.请注意:请不要将其视为对 go 的邀请,并显式初始化所有变量。 This should be done only when there is a good reason to do so, because it increases the chance of "I forgot to set this variable to the correct value" type of bugs (which would otherwise be caught by the assignment check of the C# compiler).仅当有充分理由这样做时才应这样做,因为它增加了“我忘记将此变量设置为正确值”类型错误的机会(否则会被 C# 编译器的赋值检查捕获) )。

An alternative way to initialise pairs of items is to use the C#8 "tuple" syntax, for example:初始化项目对的另一种方法是使用 C#8“元组”语法,例如:

int MyNumber = 6;

(string StringOne, string StringTwo) = 
    MyNumber != 5 ? ("Number is not 5", "True that!")
                  : ("",                ""          );

CheckNumber(StringOne, StringTwo);

The string is a reference type and the default value for all reference types is null.string是一个引用类型,所有引用类型的默认值为 null。

Try to init the StringOne and StringTwo to String.empty尝试将 StringOne 和 StringTwo 初始化为 String.empty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM