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
相关文章