编译器会为可选参数应用定制特性: System.Runtime.InteropServices.OptionAttribute
编译器会为参数默认值应用定制特性:System.Runtime.InteropServices.DefaultParameterValueAttribute
编译器会为params参数应用定制特性:System.ParamArrayAttribute
注意:调用应用了params关键字的参数方法对性能有所影响。
private static void M(Int32 x=9, String s="A",
DateTime dt=default(DateTime), Guid guid=new Guid()) {
}
private static void M(ref Int32 x) {
}
// 方法调用
Int32 a = 5;
M(x: ref a);
M(ref a);
private void AddVal(ref Int32 v)
{
v += 10;
}
private void GetVal(out Int32 v) {
v = 10; //必须初始化v
}
Int32 x;
GetVal(out x); //x不必初始化
Int32 y = 5;
AddVal(ref y); //y必须初始化
public sealed class Point {
static void Add(Point p) {}
//ref和out只能选一个来重载
//因为两个签名的元数据形式完全相同
static void Add(ref Point p) {}
//static void Add(out Point p) {}
}
using System;
using System.IO;
public sealed class Program {
public static void Main() {
FileStream fs = null; //初始化为null(必要的操作)
//打开第一个待处理的文件
ProcessFiles(ref fs);
//如果有更多需要处理的文件,就继续
for (; fs != null; ProcessFiles(ref fs)) {
//处理文件
fs.Read(...);
}
}
private static void ProcessFiles(ref FileStream fs) {
//如果先前的文件是打开的,就将其关闭
if (fs != null) fs.Close();
if (noMoreFilesToProcess) fs = null;
else fs = new FileStream(...);
}
}
public static void Swap<T>(ref T a, ref T b) {
T t = b;
b = a;
a = t;
}
static Int32 Add(params Int32[] values) {
//注意:如果愿意,可将values数组传给其他方法
Int32 sum = 0;
if (values != null) {
for (Int32 x=0; x<values.Length; x++)
sum += values[x];
}
return sum;
}