• C# ref 关键字



    ref(C# 参考)
    ref 关键字使参数按引用传递。其效果是,当控制权传递回调用方法时,在方法中对参数所做的任何更改都将反映在该变量中。若要使用 ref 参数,则方法定义和调用方法都必须显式使用 ref 关键字。例如:

     复制代码
    class RefExample
    {
        static void Method(ref int i)
        {
            i = 44;
        }
        static void Main()
        {
            int val = 0;
            Method(ref val);
            // val is now 44
        }
    }传递到 ref 参数的参数必须最先初始化。这与 out 不同,out 的参数在传递之前不需要显式初始化。(请参见 out。)

    尽管 ref 和 out 在运行时的处理方式不同,但它们在编译时的处理方式是相同的。因此,如果一个方法采用 ref 参数,而另一个方法采用 out 参数,则无法重载这两个方法。例如,从编译的角度来看,以下代码中的两个方法是完全相同的,因此将不会编译以下代码:

     复制代码
    class CS0663_Example
    {
        // compiler error CS0663: "cannot define overloaded
        // methods that differ only on ref and out"
        public void SampleMethod(ref int i) {  }
        public void SampleMethod(out int i) {  }
    }但是,如果一个方法采用 ref 或 out 参数,而另一个方法不采用这两类参数,则可以进行重载,如下所示:

     复制代码
    class RefOutOverloadExample
    {
        public void SampleMethod(int i) {  }
        public void SampleMethod(ref int i) {  }
    }< type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl12bccfc0c,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl12img,"; 备注

    属性不是变量,因此不能作为 ref 参数传递。

    有关传递数组的信息,请参见

    使用 ref 和 out 传递数组。
    < type="text/Javascript"> var ExpCollDivStr = ExpCollDivStr; ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl143faeb7d,"; var ExpCollImgStr = ExpCollImgStr; ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl14img,"; 示例

    按引用传递值类型(如上所示)是有用的,但是 ref 对于传递引用类型也是很有用的。这允许被调用的方法修改该引用所引用的对象,因为引用本身是按引用来传递的。下面的示例显示出当引用类型作为 ref 参数传递时,可以更改对象本身。

    class RefRefExample
    {
        static void Method(ref string s)
        {
            s = "changed";
        }
        static void Main()
        {
            string str = "original";
            Method(ref str);
            // str is now "changed"
        }
    }

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/cctt_1/archive/2007/08/23/1755650.aspx

  • 相关阅读:
    elastic
    Leetcode题库 第十行
    Leetcode题库-实现strStr()
    Redis持久化
    Redis的数据结构及应用场景
    Redis缓存的淘汰策略
    Redis缓存常见问题
    Redis面试题1
    消息队列的原理及选型
    【转载】java高并发/mysql/mybatis/spring博客
  • 原文地址:https://www.cnblogs.com/eastday/p/1687767.html
Copyright © 2020-2023  润新知