[转]c#可选参数和命名参数

可选参数:

应用可选参数的方法在被调用时可以选择性的添加需要的参数,而不需要的由参数默认值取代。

class Program
    {
        /// <summary>
        /// 可选参数  命名参数
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine(ShowComputer());
            Console.WriteLine(ShowComputer("P5300","1G"));
            Console.Read();
        }
 
        private static string ShowComputer(string cpu = "i3 370M", string ram = "4G", string disk = "320G")
        {
            return "My computer ... \nCpu:" + cpu + "\nRam:" + ram + "\nDisk:" + disk + "\n";
        }
    }

 

 

命名参数:
命名参数是把参数附上参数名称,这样在调用方法的时候不必按照原来的参数顺序填写参数,只需要对应好参数的名称也能完成方法。
class Program
    {
        /// <summary>
        /// 可选参数  命名参数
        /// </summary>
        static void Main(string[] args)
        {
            Console.WriteLine(ShowComputer("i3 370M","2G","320G"));
            Console.WriteLine(ShowComputer(disk: "320G", cpu: "i3 370M", ram: "2G"));
            Console.Read();
        }
 
        private static string ShowComputer(string cpu, string ram, string disk)
        {
            return "My computer ... \nCpu:" + cpu + "\nRam:" + ram + "\nDisk:" + disk + "\n";
        }
    }

 

 

命名参数可以和可选参数结合:

Console.WriteLine(ShowComputer(ram: "3G"));

程序只赋值了第二个参数ram,其他参数均为默认值,运行结果大家应该都知道了。这样命名参数和可选参数都发挥了他们独特的作用。

来自博客:https://www.cnblogs.com/weiming/archive/2011/12/28/2304937.html

posted @ 2020-06-17 21:01  穷在闹市  阅读(239)  评论(0)    收藏  举报