zoukankan      html  css  js  c++  java
  • C# ref 关键字

    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 不同,后者的参数在传递之前不需要显式初始化。

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

    class 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) {  }
    }

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

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

    namespace RefOut.Test
    {
        public class A
        {
            private string name;
            public string Name
            {
                get { return name; }
                set { name = value; }
            }
        }
        class Program
        {
            static void Method(ref string s)
            {
                s = "changed";
            }
            static void Method(string s)
            {
                s = "changed2";
            }
            static void MethodA(ref A a)
            {
                a.Name = "Summer";
            }
            static void MethodA(A a)
            {
                a.Name = "Summer";
            }
            static void Main()
            {
                A a = new A();
                a.Name = "Jeriffe";
                MethodA(ref a);
                //A.Name is Summer
                Console.WriteLine(a.Name);

                a.Name = "Jeriffe";
                MethodA(a);
                //A.Name is Summer
                Console.WriteLine(a.Name);
                
                string str = "original";
                Method(ref str);
                // str is now "changed"
                Console.WriteLine(str);

                str = "original";
                Method(str);//str是一个引用不是str对象本身,是以pass by value的方式传递的,所以Method只能变更str的内容,不能变更str引用
                // str is now "original"
                Console.WriteLine(str);
     
                Console.Read();
            }
        }}
  • 相关阅读:
    DS02--线性表
    DS01--抽象数据类型
    C语言最后一次作业--总结报告
    C语言第十一次作业--函数嵌套调用
    你还有很多要学的东西
    Google Guice 系列教程 - 基础实践
    Eclim指令集
    maven入门案例
    从java调用groovy
    linux下安装Groovy环境
  • 原文地址:https://www.cnblogs.com/jeriffe/p/1809211.html
Copyright © 2011-2022 走看看