Java 中 C# 的 ref 和 out
众所周知,两种语言在将参数传递给方法时都是按值传递的。但 C# 支持 ref
和 out
关键字来传递基本类型的引用。我正在 Java 中寻找相同的关键字和技术?
我的猜测是使用Integer
包装类而不是Java中的int
来传递。
有什么建议和例子吗?
As we know both language are pass-by-value when passing parameters to methods. But C# supports ref
and out
keywords to pass-by-reference of primitive types. I am looking for the same keywords and technique in Java?
My guess is using Integer
wrapper class instead of int
in Java to pass in.
Any suggestions and examples?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你的猜测是正确的。需要一个包装器(但不需要 Integer,因为它是不可变的)。
有些人使用单元素数组来达到此目的:
许多人会将该技术与 GOTO 放在一起。
有些人定义通用持有者类:
有些人定义专用类型:
有些人会安排在方法内部完成工作,首先避免对引用参数的需要:
这些技术中的每一种都有优点和缺点:
就我个人而言,我认为Java 在这方面搞砸了。我宁愿避免通过引用参数,但我希望 Java 允许一个方法有多个返回值。但说实话,我并不经常被这个问题绊倒。我不会为了这个功能而付出肾脏。 :)
Your guess is correct. A wrapper is needed (but not Integer as it is immutable).
Some people use single element arrays for this purpose:
Many will rank that technique right up there with GOTO.
Some people define a generic holder class:
Some define a purpose-built type:
Some would arrange for the work to be done inside the method, avoiding the need for by-reference arguments in the first place:
Each of these techniques has advantages and disadvantages:
Personally, I think that Java messed up on this one. I'd rather avoid by-reference arguments, but I wish Java permitted multiple return values from a method. But, truthfully, I don't trip over this one very often. I wouldn't give a kidney for this feature. :)
Java 不支持此功能。
Java does not support this feature.
Java 不支持通过引用传递基本类型。
将
int
包装为Integer
不会有帮助,因为它是不可变类型(即一旦创建就无法更改)。Java does not support passing primitive types by reference.
Wrapping an
int
as anInteger
won't help, since it is an immutable type (i.e. cannot be changed once created).Java没有这个内置的。
Integer
不行,因为它是不可变的。你无法改变它的状态。您必须创建自己的可变包装类。但这是非常“危险”的,可能会导致意想不到的结果,所以尽量避免。
Java does not have this built-in.
Integer
won't do, because it is immutable. You can't change its state.You will have to create your own mutable wrapper class. But this is very "dangerous" and may lead to unexpected results, so try to avoid it.
传回值的唯一方法是传递对可变值的引用,
但是最简单的方法是返回所有更改的值
The only way to pass value back is to pass a reference to a mutable value like
however the simplest thing to do is to return all changed values
Java 没有此功能
,这里是 Java 与 C# 比较的链接
http://www.harding.edu /fmccown/java_csharp_comparison.html
这就是为什么他们称 Java 为非纯 OOP 语言
Java dont have this feature
here is a link to Java vs C# comparison
http://www.harding.edu/fmccown/java_csharp_comparison.html
thats why they call Java a non pure OOP language