当前位置:网站首页>具名参数

具名参数

2023-01-19 15:33:03阿斯提尼

当我们在调用参数很多的且具有可选参数的方法时就可以用到具名参数,比如:
有一个方法

     public class ParameterClass
            {
    
                public void TestFunc(int a, bool b = false, string c = null, int d = 0, int e = 0)
                {
    
                    if (b)
                    {
    
                        Console.WriteLine("第二个参数b = " + b);
                    }
                    if (!string.IsNullOrEmpty(c))
                    {
    
                        Console.WriteLine("第三个参数c = " + c);
                    }
                    if (d != 0)
                    {
    
                        Console.WriteLine("第四个参数d = " + d);
                    }
                    if (e != 0)
                    {
    
                        Console.WriteLine("第五个参数e = " + e);
                    }
                    Console.ReadKey();
                }
            }

正常情况下我们如果想给e赋值,而其它参数采用默认值时我们一般将所有的参数都列出来,这种操作在参数很多的情况下很费时且很容易出错(例子只举了5个参数,而实际我们有可能会遇到10个、20个等参数的情况)

	new ParameterClass().TestFunc(0, false, null, 0, 666666);

而使用具名参数就可以很轻松地给特定的参数赋值,简单还不容易出错,此时采用具名参数我们就可以这样做:

 	new ParameterClass().TestFunc(0, c: "HelloWorld", e: 666666);

得到的结果如下:
输出结果

原网站

版权声明
本文为[阿斯提尼]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_43112045/article/details/88671357

随机推荐