簡體   English   中英

如何在C#函數調用中找到缺少的參數?

[英]How can I find the missing parameters in a C# function call?

當缺少C#函數中的命名參數時,編譯器僅輸出缺少數量的參數,而不打印函數中每個缺少參數的名稱:

prog.cs(10,27): error CS1501: No overload for method `createPrism' takes `2' arguments`.

但是,出於調試目的,通常有必要獲取函數調用中缺少的參數的名稱,特別是對於帶有許多參數的函數。 是否可以在C#函數調用中打印缺少的參數?

using System;
public class Test{
    public static int createPrism(int width, int height, int length, int red, int green, int blue, int alpha){
        //This function should print the names of the missing parameters
        //to the error console if any of its parameters are missing. 

        return length*width*height;
    }
    static void Main(){
        Console.WriteLine(getVolume(length: 3, width: 3));
        //I haven't figured out how to obtain the names of the missing parameters in this function call.
    }
}

您可以使所有參數為空,並將它們設置為默認值。 然后,在您的方法中,您可以檢查哪些參數具有空值並對其進行處理。

   public static int createPrism(int? width=null, int? height=null){
       if(!height.HasValue){
         Console.Write("height parameter not set")
       }
   }

我唯一想到的就是使用可選參數:

public static int createPrism(int width = -1, int height = -1, int length = -1, int red = -1, int green = -1, int blue = -1, int alpha = -1){
    if(width == -1)
        Console.WriteLine("Invalid parameter 'width'");
    if(height == -1)
        Console.WriteLine("Invalid parameter 'height'");
    ...

    return length*width*height;
}

在以下情況下,這將打印出正確的結果:

createPrism(length: 3, width: 3);

但是,沒有什么可以阻止用戶編寫如下內容:

createPrism(width: -1, height: -1);

亞歷克斯的答案是同樣有效的另一種形式。 技巧是確保默認值不是有效的參數值。


另一種技術是使用參數字典

public static int createPrism(Dictionary<string, int> parameters){
    if(!parameters.ContainsKey("width"))
        Console.WriteLine("Missing parameter 'width'");
    if(!parameters.ContainsKey("height"))
        Console.WriteLine("Missing parameter 'height'");
    ...

    return parameters["length"] * parameters["width"] * parameters["height"];
}

但是調用它變得非常麻煩:

createPrism(new Dictionary<string, int>() { { "length", 3 }, { "width", 3 } });

您可以使用dynamic參數類型在某種程度上克服這一問題:

public static int createPrism(dynamic parameters){
    if(parameters.GetType().GetProperty("width") == null)
        Console.WriteLine("Invalid parameter 'width'");
    if(parameters.GetType().GetProperty("height") == null)
        Console.WriteLine("Invalid parameter 'height'");
    ...

    return parameters.length * parameters.width * parameters.height;
}

變成:

createPrism(new { length: 3, width: 3 });

盡管最終,最好的選擇只是讓編譯器完成任務。 您的原始聲明足以確保調用代碼提供了所有必要的參數,以使函數成功返回。 通常,如果函數可以在沒有給定參數的情況下執行,則應將其設為可選(通過默認值或使用忽略該函數的重載),然后編譯器將負責其余工作。 您只需要擔心調用者提供的是否有效。

暫無
暫無

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

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