欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-09-27 22:23:55
Java没有引用传递机制,C#有: public class Obj { private Integer myValue; public Integer getMyValue() { return myValue; } public void setMyValue(Integer myValue) ......

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);
    }
}
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;
        }
    }
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