实际上,据我所知,在Java语言中并没有ref或out关键字的等效物。然而,我刚刚将一个使用out参数的C#代码转换为了Java,并会告诉你我刚刚做了什么。您应该将任何对象包装到包装类中,并像下面这样传递封装在包装对象实例中的值;
使用包装器的简单示例
这是包装器类;
public class Wrapper {
public Object ref1;
public Object ref2;
public Wrapper(Object ref1) {
this.ref1 = ref1;
}
}
这里是测试代码:
public class Test {
public static void main(String[] args) {
String abc = "abc";
changeString(abc);
System.out.println("Initial object: " + abc);
Wrapper w = new Wrapper(abc);
changeStringWithWrapper(w);
System.out.println("Updated object: " + w.ref1);
System.out.println("Out object: " + w.ref2);
}
public static void changeString(String str) {
str = "def";
}
public static void changeStringWithWrapper(Wrapper w) {
w.ref1 = "def";
w.ref2 = "And this should be used as out!";
}
}
一个现实世界的例子
使用out参数的C#.NET方法
这里有一个使用out关键字的C#.NET方法;
public bool Contains(T value)
{
BinaryTreeNode<T> parent;
return FindWithParent(value, out parent) != null;
}
private BinaryTreeNode<T> FindWithParent(T value, out BinaryTreeNode<T> parent)
{
BinaryTreeNode<T> current = _head;
parent = null;
while(current != null)
{
int result = current.CompareTo(value);
if (result > 0)
{
parent = current;
current = current.Left;
}
else if (result < 0)
{
parent = current;
current = current.Right;
}
else
{
break;
}
}
return current;
}
使用out参数的C#代码对应的Java代码
借助包装类,下面是这个方法的Java版本:
public boolean contains(T value) {
BinaryTreeNodeGeneration<T> result = findWithParent(value);
return (result != null);
}
private BinaryTreeNodeGeneration<T> findWithParent(T value) {
BinaryTreeNode<T> current = head;
BinaryTreeNode<T> parent = null;
BinaryTreeNodeGeneration<T> resultGeneration = new BinaryTreeNodeGeneration<T>();
resultGeneration.setParentNode(null);
while(current != null) {
int result = current.compareTo(value);
if(result >0) {
parent = current;
current = current.left;
} else if(result < 0) {
parent = current;
current = current.right;
} else {
break;
}
}
resultGeneration.setChildNode(current);
resultGeneration.setParentNode(parent);
return resultGeneration;
}
包装类
这段Java代码中使用的包装类如下所示:
public class BinaryTreeNodeGeneration<TNode extends Comparable<TNode>> {
private BinaryTreeNode<TNode> parentNode;
private BinaryTreeNode<TNode> childNode;
public BinaryTreeNodeGeneration() {
this.parentNode = null;
this.childNode = null;
}
public BinaryTreeNode<TNode> getParentNode() {
return parentNode;
}
public void setParentNode(BinaryTreeNode<TNode> parentNode) {
this.parentNode = parentNode;
}
public BinaryTreeNode<TNode> getChildNode() {
return childNode;
}
public void setChildNode(BinaryTreeNode<TNode> childNode) {
this.childNode = childNode;
}
}
TryParse()
这样的模式时才会使用ref
或out
,其中方法返回一个布尔结果,通过使用ref
或out
是获取解析值的唯一方法。 - Robert Harvey