在方法中传递参数,在if-else语句C#中传递参数

本文关键字:参数 语句 方法 if-else | 更新日期: 2023-09-27 18:24:48

我正在编写一个方法,该方法可以接受一定数量的参数,并包含一个if-else语句。当我使用命令行参数时,我会传入至少3个参数,最多4个参数。

当我只使用3个参数运行命令行时,它应该只运行if的第一部分。只有当我必须传递第四个参数时,它才会运行else,但每次我运行四个参数,代码都不会到达else,只运行if语句的开头。任何想法都值得赞赏

protected void net_group(string command, string param1, string param2, string param3)
        {

Console.WriteLine("Got information net group command");
        //creates group.txt file when "net group" command is used
        string path = "C:''Files''groups.txt";
        using (StreamWriter sw = File.AppendText(path))
        {
            sw.WriteLine(param2 + ": " + param3); //param2 is name of the group //param3 is name of user
        }
            if (not sure what argument would go here) {
                //writes to the audit log and to the console when group is made w/out users
                Console.WriteLine("Group " + param2 + " created");
                string path2 = "C:''Files''audit.txt";
                using (StreamWriter sw2 = File.AppendText(path2))
                {
                    sw2.WriteLine("Group " + param2 + " created");
                }
            }
            else
            {
                //writes to the audit log and to the console when user is added to a new group

//currently the method wont reach here even when I pass four parameters
                Console.WriteLine("User " + param3 + " added to group " + param2 + "");
                string path3 = "C:''Files''audit.txt"; //doesnt write this to audit.txt
                using (StreamWriter sw3 = File.AppendText(path3))
                {
                    sw3.WriteLine("User " + param3 + " added to group " + param2 + "");
                }
            }
            Console.Read();

在方法中传递参数,在if-else语句C#中传递参数

查看方法的签名,最好的解决方案是使用以下内容:

if (String.IsNullOrEmpty(param3)) // you could say that only 3 params were given
{
}
else // you could say that all 4 params were given
{
}

看看这个Microsoft教程。

我想你的代码会是这样的:

    static void Main(string[] args)
    {
        ...
        if (args.Length == 3) {
        //writes to the audit log and to the console when group is made w/out users
        Console.WriteLine("Group " + args[1] + " created");
        string path2 = "C:''Files''audit.txt";
        using (StreamWriter sw2 = File.AppendText(path2))
        {
            sw2.WriteLine("Group " + args[1] + " created");
        }
    }
    else
    {
        //writes to the audit log and to the console when user is added to a new group

正如教程所指出的,您还可以使用Environment.CommandLine或Environment.GetCommandLineArgs从控制台或Windows应用程序中的任何点访问命令行参数。