zoukankan      html  css  js  c++  java
  • C# 关于out和ref的问题

    http://bbs.csdn.net/topics/320214035

    问题:

    C#里非基础类型传参数都是以引用类型的方式,
    那么换句话说,out和ref除了基础类型外,实际上没有任何意义?
    是不是这么个意思?

    答案:

    对于引用类型来说
    不加out和ref,你可以修改这个对象的属性
    加了out和ref,你可以使这个变量指向一个新的对象~

    实例:

    看看下面别人发过的你就明白了

    using System.Collections.Generic; 
    using System.Text; 
    using System; 
    
    namespace ConsoleApplication1 
    { 
        class Value 
        { 
            public int i = 15; 
        } 
        class Program 
        { 
            static void Main(string[] args) 
            { 
                Program t = new Program(); 
                t.first(); 
            } 
            public void first() 
            { 
                int i = 5; 
                Value v = new Value(); 
                v.i = 25; 
                second(v, i); 
                Console.WriteLine(v.i);//20 
            } 
            public void second(Value v, int i) 
            { 
                i = 0;  
                v.i = 20; 
                Value val = new Value(); 
                v = val;//此处t被指向了val的地址,和原先的v断开了联系
                Console.WriteLine(v.i + " " + i + " ");//15,0 
            } 
        } 
    } 
    
    
    15 0 
    20 
    
    
    using System.Collections.Generic; 
    using System.Text; 
    using System; 
    
    namespace ConsoleApplication1 
    { 
        class Value 
        { 
            public int i = 15; 
        } 
        class Program 
        { 
            static void Main(string[] args) 
            { 
                Program t = new Program(); 
                t.first(); 
            } 
            public void first() 
            { 
                int i = 5; 
                Value v = new Value(); 此时v.i=15,i=5 
                v.i = 25; 
                second(ref v, i); 
                Console.WriteLine(v.i);//20 
            } 
            public void second(ref Value v, int i) 
            { 
                i = 0;  
                v.i = 20; 
                Value val = new Value(); 
                v = val;
                Console.WriteLine(v.i + " " + i + " ");//15,0 
            } 
        } 
    } 
    
    15 0 
    15

    附加说明:

    out修饰的参数,可以用没有被初始化变量传递给函数,但在函数内必须被赋值。
    ref修饰的参数,不可以用没有被初始化的实际参数。但在函数内可以不被赋值。

  • 相关阅读:
    topcoder srm 445 div1
    topcoder srm 440 div1
    topcoder srm 435 div1
    topcoder srm 430 div1
    topcoder srm 400 div1
    topcoder srm 380 div1
    topcoder srm 370 div1
    topcoder srm 425 div1
    WKWebView强大的新特性
    Runtime那些事
  • 原文地址:https://www.cnblogs.com/zouhao/p/3246130.html
Copyright © 2011-2022 走看看