假设我想编写一个返回User对象的方法,并且我想修改UserStatus枚举。
在c#中我能做到:
public User InsertNewUser(User newUser, out UserStatus userStatus)
{
}
out(http://msdn.microsoft.com/en-us/library/t3c3bfhx(v=vs.80).aspx)基本上给了我多个“返回”的对象。
如果java有这个好奇吗?
答案 0 :(得分:1)
您无法修改传入的UserStatus引用,因为Java是按值传递的,但如果它是可变的,您可以更改其状态。
public class UserStatus {
private String status;
public static void main(String [] args) {
String name = ((args.length > 0) ? args[0] : "stas");
User user = new User(name);
UserStatus status = new UserStatus();
System.out.println(String.format("before: user %s status %s\n", user.toString(), status.toString()));
user = insertNewUser(user, status);
System.out.println(String.format("after : user %s status %s\n", user.toString(), status.toString()));
}
public static User insertNewUser(User user, UserStatus status) {
User newUser = new User(user.getName() + "-changed");
status = new UserStatus("SUCCESS"); // Won't work as expected because Java is pass by value
//status.setStatus("SUCCESS"); // Uncomment this and see that it's the only way to change the status flag
return user;
}
public UserStatus() { this.status = "UNKNOWN"; }
public UserStatus(String value) { this.status = value; }
public String getStatus() { return this.status; }
public void setStatus(String status) { this.status = status; }
public String toString() { return this.status; }
}
class User {
private final String name;
public User(String name) { this.name = name; }
public String getName() { return this.name; }
public String toString() { return this.name; }
}
答案 1 :(得分:0)
Java没有类似的东西。变量将通过引用传递,因此您可以执行:
UserStatus myStatus = new UserStatus();
User myUser = insertNewUser(someUser, myStatus);
System.out.println(myStatus);
上面,myStatus将由您的函数更新,但正如您所看到的,您需要在传递之前对其进行初始化,这与C#out变量不同。
答案 2 :(得分:-1)
如果您想修改userStatus
,则隐含out
而非隐含。如果您将userStatus
设置为新对象,则它将引用该新对象。