函數調用時,參數帶形參及冒號


看到下面的語法,其他語言都沒見過這種語法

int GetValue(string prompt, int min, int max)
{
    int result;
    do
    {
        result = SnapsEngine.ReadInteger(prompt);
    } while (result < min || result > max);
    return result;
}
int age = GetValue(prompt: "Enter your age in years", min: 0, max: 100);
int height = GetValue(prompt: "Enter your height in inches", min: 30, max: 96);

然后在stack overflow上看到使用冒號的各種情形:

https://stackoverflow.com/questions/17034475/in-c-sharp-what-category-does-the-colon-fall-into-and-what-does-it-really  

作用就是,指定形參名:

Console.WriteLine(value: "Foo");

value一定要與聲明中的形參名一致,不能改成其他名稱,否則出錯,所以, 猜測就是,冒號前的是形參名,冒號后的是實參,如果不用這種寫法,參數順序一定不能亂,如果使用這種語法,對參數位置沒有要求,可以隨意寫。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM