可选参数简介 - C#4.0






2.96/5 (22投票s)
本文介绍了使用可选参数的好处
引言
C#4.0 引入了新的可选参数,为开发者提供了灵活地传递参数的能力。
背景
考虑以下 C#3.0 中的示例
class Program { static void Main(string[] args) { WithoutNamedParameter(null,null); //Print default values WithoutNamedParameter("Some Name", null); //Print only default age WithoutNamedParameter(null, 25); //Print only default name WithoutNamedParameter("Some Name", 50); //Print the value passed Console.ReadKey(true); } private static void WithoutNamedParameter(string name, int? age) { string _name = "Default Name"; int? _age = 18; //Check if name is empty or not and hence assign if (!string.IsNullOrEmpty(name)) _name = name; //Check if age is empty or not and hence assign if (age.HasValue) _age = age; Console.WriteLine(string.Format("{0},your age is {1}", _name, _age)); } }
在 WithoutNamedParameter 方法中,我们首先为两个变量 _name 和 age 分别赋了两个默认值。然后,我们检查调用函数是否为方法参数赋了任何值,并根据该值显示这些值。
接下来,请看调用函数。该方法 WithoutNamedParameter 使用四个不同的值被调用了四次。但代码看起来很糟糕。
另一种选择是创建四个重载的方法来满足需求,如果需要避免空值或空引用检查,但这又是一项繁琐的工作。
C#4.0 引入的新可选参数看起来更好。
可选参数
考虑以下用 C#4.0 编写的程序
class Program { static void Main(string[] args) { MethodWithOptionalParameters();//Print default values MethodWithOptionalParameters("Some Name");//Print only default age MethodWithOptionalParameters(Age: 25);//Ask to print only Name //Prints the values passed MethodWithOptionalParameters("Some Other Name", 20); Console.ReadKey(true); } private static void MethodWithOptionalParameters (string Name = "Default Name", int Age = 18) { Console.WriteLine(string.Format("{0}, your age is {1}",Name,Age)); } }
可以看出,在新代码中,我们不再检查方法参数的空值/空引用值。相反,我们为方法参数赋了默认值。
考虑第一个调用方法。我们根本没有传递任何参数。编译器会愉快地编译通过(这与前面的示例不同,它会报告错误:没有重载方法 'WithoutNamedParameter' 接受 '0' 个参数)。
代码的 IL 如下所示
这表明可选参数存在于 MSIL 中。
考虑第三个方法调用
MethodWithOptionalParameters(Age: 25);//仅要求打印 Name
在这里,我们仅指定 Age,这在本例中是一个命名参数,编译器会理解并执行此操作。
最终输出为
结论
在本文中,我们简要了解了可选参数如何帮助开发者避免编写重载的方法,并提高代码的可重用性。
非常感谢您对该主题的评论,以便改进该主题。
感谢阅读本文。