在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
刚学习Java不久,今天遇到一个问题,需要在方法中修改传入的对象的值,确切的说是需要使用一个方法,创建一个对象,并把其引用返回,熟悉C#的我 参数传递: 值传递:就是把传递的【数据本身拷贝一份】,传入方法中对其进行操作,拷贝的是值。 那么就我当前的问题而言,我需要一个方法,我传入一个引用,在方法中创建所需对象. 那么在Java中就会只能给当前对象在封装一层(定义一个新类),使得需要创建的对象成为新类的成员,在方法中为成员赋值
C#: /// <summary>
/// model
/// </summary>
public class Student { public string Name; public int Age; } /// 方法:
/// <summary>
/// 错误示范
///
/// student这个引用是拷贝传入的,创建新的对应Student
/// 把引用赋给student,当方法退栈之后student引用回到压栈前
/// 则Student对象引用数为0,等待GC,引用student依旧是原来的值(逻辑地址)
/// </summary>
/// <param name="student"></param>
static void createStudent(Student student) { student = new Student { Name ="Stephen Lee", Age = 1}; } /// <summary>
/// 正确做法
///
/// 通过ref关键字,把操作权让给方法内部
/// </summary>
/// <param name="student"></param>
static void createStudent(ref Student student) { student = new Student { Name = "Stephen Lee", Age = 1 }; } // Client
static void Main(string[] args) { Console.WriteLine("错误示范");
Student student1 = null;
createStudent(student1); if (student1 == null) Console.WriteLine("创建对象失败");
else
Console.WriteLine("创建对象成功,Name:" + student1.Name);
Console.WriteLine("正确做法");
Student student2 = null;
createStudent(ref student2);
if (student2 == null) Console.WriteLine("创建对象失败");
else
Console.WriteLine("创建对象成功,Name:" + student2.Name);
}
Java: /** Model
* @author Stephen
*
*/
public class Student { public String Name;
public int Age; public Student(String name,int age) { this.Name = name;
this.Age = age;
} } /** 错误示范,原因同C#
* @param student
*/
private void createStudent(Student student) { student = new Student("Stephen Lee",1); } /** 正确做法
* @param studentPack
*/
private void createStudent(StudentPack studentPack) { studentPack.student = new Student("Stephen Lee",1); } /** 包装器
* @author Stephen
*
*/
public class StudentPack { public Student student;
}
// Client
StudentPack studentPack = new StudentPack();
createStudent(studentPack); System.out.println(studentPack.student.Name);
ref/out关键字:http://msdn.microsoft.com/zh-cn/library/14akc2c7.aspx |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论