簡體   English   中英

在if-else語句C#中的方法中傳遞參數

[英]Passing parameters in a method, in an if-else statement C#

我正在寫一個可以接受一定數量參數並包含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 (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應用程序中的任何位置訪問命令行參數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM