一、可选参数和命名参数
在设计一个方法的参数时,可为部分或全部参数分配默认值。然后,调用这些方法的代码时可以选择不指定部分实参,接受默认值。此外,调用方法时,还可以通过指定参数名称的方式为其传递实参。比如:
internal static class Program { private static Int32 s_n = 0; private static void M(Int32 x=9, String s = "A", DateTime dt = default(DateTime), Guid guid = new Guid()) { Console.WriteLine("x={0}, s={1}, dt={2}, guid={3}, x, s, dt, guid"); } public static void Go() { // 1.等同于: M(9, "A", default(DateTime), new Guid()); M(); // 2. 等同于: M(8, "X", default(DateTime), new Guid()); M(8, "X"); // 3. 等同于: M(5, "A", DateTime.Now, Guid.NewGuid()); M(5, guid: Guid.NewGuid(), dt: DateTime.Now); // 4. 等同于: M(0, "1", default(DateTime), new Guid()); M(s_n++, s_n++.ToString()); // 5. 等同于s: String t1 = "2"; Int32 t2 = 3; // M(t2, t1, default(DateTime), new Guid()); M(s: (s_n++).ToString(), x: s_n++); }
}
// 方法声明 private static void M(ref Int32 x) { ... } // 方法调用 Int32 a = 5; M(x: ref a); .....
二、隐式类型的局部变量
针对一个方法中的隐式类型的局部变量,C#允许根据初始化表达式的类型来判断它的类型。
private static void ImplicitlyTypedLocalVariables() { var name = "Jeff"; ShowVariableType(name); // 类型是: System.String // var n = null; // 错误 var x = (Exception)null; // 可以这样写,但没意义 ShowVariableType(x); // 类型是: System.Exception var numbers = new Int32[] { 1, 2, 3, 4 }; ShowVariableType(numbers); // 类型是: System.Int32[] // 针对复杂类型,可减少打字量 var collection = new Dictionary<String, Single>() { { ".NET", 4.0f } }; // 类型是: System.Collections.Generic.Dictionary`2[System.String,System.Single] ShowVariableType(collection); foreach (var item in collection) { // 类型是: System.Collections.Generic.KeyValuePair`2[System.String,System.Single] ShowVariableType(item); } }
private static Int32 Add(params Int32[] values) { Int32 sum = 0; for (Int32 x = 0; x < values.Length; x++) sum += values[x]; return sum; }
params关键字只能应用于方法参数列表的最后一个参数。
//显示 "15" Console.WriteLine(Add(new Int32[] { 1, 2, 3, 4, 5 }));
也可以这样:
// 显示 "15" Console.WriteLine(Add(1, 2, 3, 4, 5));
// 显示"0" Console.WriteLine(Add()); Console.WriteLine(Add(null));
private static void DisplayTypes(params Object[] objects) { foreach (Object o in objects) Console.WriteLine(o.GetType()); }
五、参数和返回类型的指导原则
//好 public void MainpulateItems<T>(IEnumerable<T> collection) { ... } //不好 public void MainpulateItems<T>(IEnumerable<T> collection) { ... } //好:该方法使用弱参数类型 public void ProcessBytes(Stream someStream) { ... } //不好:该方法使用强参数类型 public void ProcessBytes(Stream someStream) { ... }
2)一般最好将方法的返回类型声明为最强的类型,以免受限于特定类型。例如:
//好:该方法使用强返回值类型 public FileStream ProcessBytes() { ... } //不好:该方法使用弱返回值类型 public Stream ProcessBytes() { ... }
六、常量性
CLR没有提供对常量参数/对象的支持。原文:http://www.cnblogs.com/zxj159/p/3544227.html