C#关键字 params、checked、unchecked、ref、out

文章介绍了C#中的可变参数params,以及checked和unchecked语句对整数溢出的不同处理方式。同时对比了ref和out关键字在函数参数传递中的作用和要求。
摘要由CSDN通过智能技术生成

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
  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值