Java是否有类似C#的ref和out关键字的东西?

2022-08-31 08:17:36

如下所示:

参考示例:

void changeString(ref String str) {
    str = "def";
}

void main() {
    String abc = "abc";
    changeString(ref abc);
    System.out.println(abc); //prints "def"
}

示例:

void changeString(out String str) {
    str = "def";
}

void main() {
    String abc;
    changeString(out abc);
    System.out.println(abc); //prints "def"
}

答案 1

不,Java没有像C#这样的东西和关键字来传递引用。refout

在 Java 中只能按值传递。甚至引用也是按值传递的。有关更多详细信息,请参阅 Jon Skeet 关于 Java 中参数传递的页面。

要执行类似于或必须将参数包装在另一个对象中,并将该对象引用作为参数传入。refout


答案 2

直接回答:没有

但是,您可以使用包装器模拟引用

并执行以下操作:

void changeString( _<String> str ) {
    str.s("def");
}

void testRef() {
     _<String> abc = new _<String>("abc");
     changeString( abc );
     out.println( abc ); // prints def
}

void setString( _<String> ref ) {
    str.s( "def" );
}
void testOut(){
    _<String> abc = _<String>();
    setString( abc );
    out.println(abc); // prints def
}

基本上任何其他类型,例如:

_<Integer> one = new <Integer>(1);
addOneTo( one );

out.println( one ); // May print 2

推荐