params
params是一个计算机函数,表示函数的参数是可变个数的,即可变的方法参数,用于表示类型相同,但参数数量不确定。
static void Main(string[] args)
{
Show("1","我","你好");//调用Show方法时可以传任意个数的string类型的实参
}
public static void Show(params string[]strs )//params修饰的string类型的形参数组
{
}
checked、unchecked
checked 和 unchecked 语句指定 整型类型 算术运算和转换的溢出检查上下文。
当发生整数算术溢出时,溢出检查上下文将定义发生的情况。
在未检查(unchecked)的上下文中,会通过丢弃任何不适应目标类型的高序位来将操作结果截断。
在已检查(checked)的上下文中,引发System.OverflowException;如果在常数表达式中发生溢出,则会发生编译时错误。
uint a = uint.MaxValue;
Console.WriteLine(a + 3); // output: 2 默认不检查
unchecked
{
Console.WriteLine(a + 3); // output: 2
}
try
{
checked
{
Console.WriteLine(a + 3);
}
}
catch (OverflowException e)
{
Console.WriteLine(e.Message); // output: Arithmetic operation resulted in an overflow.
}
ref、out
ref
不使用 ref和使用ref的区别
//不使用 ref;
void Method(int myRefInt)
{
myRefInt += 66;
}
int number = 1;
Method(number);
Console.WriteLine(number);
**//输出 : 1;**
//使用ref
void Method(ref int myRefInt)
{
myRefInt += 66;
}
int number = 1;
Method(ref number);
Console.WriteLine(number);
**//输出:67**
看到这里想必已经明白了:
不使用ref的时候,函数收到的值是1,然后在Method(int myRefInt)方法中,局部变量myRefInt做了累加之后,在方法执行完成之后就已经销毁了。number的值还是1。
使用ref的时候,函数Method(ref int myRefInt)值收到的是number的地址,函数中执行的myRefInt+=66;此时相当于number+=66;直接修改了number地址的值。
那就可以等处结论了:ref是通过给方法传递值类型的参数,直接操作同一个变量的关键字。
out的用法
int number;
Method(number);
void Method(int myRefInt)
{
myRefInt = 66;
}
Console.WriteLine(number);
//输出:0
int number;
Method(out number);
void Method(out int myRefInt)
{
myRefInt = 66;
}
Console.WriteLine(number);
//输出:66
从上述out用法的表现来看,out和ref其实都可以允许通过引用来传递参数。那么问题来了既然ref 、out的作用看起来一样,为什么还定义了两个关键字呢?
就是:当你在使用ref传递参数的时候,ref修饰的参数必须要有值,但是out可以使用一个未赋值的变量作为参数传递。下面我也用代码做了验证。
int x;
Foo(out x); //ok
int y;
Foo(ref y); //Erroy: y should be initialized before calling the method