zoukankan      html  css  js  c++  java
  • C# ref和out的区别

    一、ref(引用型参数)和out(输出型参数)的区别

    1、使用ref型参数时,传入的参数必须先被初始化,out型参数,必须在方法中对其完成初始化。

    2、使用ref和out时,在方法的参数和执行方法时,都要加Ref或Out关键字,以满足匹配。

    3、out适合用在需要retrun多个返回值的地方,而ref则用在需要被调用的方法修改调用者的引用的时候。

    4、ref传进去的参数在函数内部可以直接使用,而out不可。

    5、系统对ref的限制是更少一些的。

    6、若要使用 ref 参数,必须将参数作为 ref 参数显式传递到方法,ref 参数的值被传递到 ref 参数。

    7、当希望方法返回多个值时,声明 out 方法非常有用;使用 out 参数的方法仍然可以返回一个值。

    8、ref 将值类型强制按引用类型进行传递

    二、代码举例

     1 class Program
     2     {
     3         static void Main(string[] args)
     4         {
     5 
     6             T t = new T();
     7             t.num = 5;
     8             ChangeT(ref t);
     9             Console.WriteLine(t.num);
    10             string str;
    11             string result;
    12             result = Handle(out str);
    13             Console.WriteLine(str);
    14             Console.WriteLine(result);
    15         }
    16 
    17         static string Handle(out string s)
    18         {
    19             s = "hello";
    20             return "ok";
    21         }
    22 
    23         static void ChangeT(ref T t)
    24         {
    25             t.num++;
    26         }
    27     }
  • 相关阅读:
    11前端css动画
    10前端css文本和字体
    09前端css3渐变
    08前端css3背景
    07前端css3边框和圆角
    06前端css3增加选择器
    堡垒机Teleport
    Sublime Text 3注册及中文乱码问题解决
    Linux部署KMS激活Windows 10和Office 2016
    服务器维护实施步骤
  • 原文地址:https://www.cnblogs.com/mojiejushi/p/13220609.html
Copyright © 2011-2022 走看看