Java没有引用传递机制,C#有。

2019-08-16 09:10:27来源:博客园 阅读 ()

新老客户大回馈,云服务器低至5折

Java没有引用传递机制,C#有。

Java没有引用传递机制,C#有:

public class Obj {
    private Integer myValue;

    public Integer getMyValue() {
        return myValue;
    }

    public void setMyValue(Integer myValue) {
        this.myValue = myValue;
    }
}

public class ObjOperation {
    public void changeValue(Obj obj) {
        obj.setMyValue(1);
    }
    
    public void changeValue2(Obj obj) {
        obj = new Obj();
        obj.setMyValue(2);
    }
}
Java 对象及操作类定义
public class MyApp {

    public static void main(String[] args) {
        Obj obj = new Obj();
        obj.setMyValue(0);
        System.out.println(obj.getMyValue());
        
        ObjOperation refOperation = new ObjOperation();
        
        refOperation.changeValue(obj);
        System.out.println(obj.getMyValue());
        
        refOperation.changeValue2(obj);
        System.out.println(obj.getMyValue());
    }

}

运行结果:

0
1
1

    public class Obj
    {
        private int myValue;
        public int MyValue { get => myValue; set => myValue = value; }
    }

    public class ObjOperation
    {
        public void ChangeValue(Obj obj)
        {
            obj.MyValue = 1;
        }

        public void ChangeValue2(Obj obj)
        {
            obj = new Obj();
            obj.MyValue = 2;
        }

        /// <summary>
        /// 引用传递
        /// </summary>
        /// <param name="obj"></param>
        public void ChangeValue3(ref Obj obj)
        {
            obj = new Obj();
            obj.MyValue = 2;
        }
    }
C# 对象及操作类定义
class Program
    {
        static void Main(string[] args)
        {
            Obj obj = new Obj();
            obj.MyValue = 0;
            Console.WriteLine(obj.MyValue);

            ObjOperation objOperation = new ObjOperation();
            objOperation.ChangeValue(obj);
            Console.WriteLine(obj.MyValue);

            objOperation.ChangeValue2(obj);
            Console.WriteLine(obj.MyValue);

            //引用传递
            objOperation.ChangeValue3(ref obj);
            Console.WriteLine(obj.MyValue);

            Console.Read();
        }
    }

运行结果:

0
1
1
2


原文链接:https://www.cnblogs.com/penqiji/p/11082947.html
如有疑问请与原作者联系

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:初识MyBatis之HelloWorld

下一篇:高级Java工程师必备 ----- 深入分析 Java IO (二)NIO