您可以通过Java的引用传递? [英] Can you pass by reference in Java?
问题描述
很抱歉,如果这听起来像一个新手的问题,但有一天,一个Java开发者引用传递一个放慢参数(由它被换货只是传递一个参考对象)
Sorry if this sounds like a newbie question, but the other day a Java developer mentioned about passing a paramter by reference (by which it was ment just pass a Reference object)
从C#的角度来看,我可以通过值或引用传递引用类型,这也是千真万确的值类型
From a C# perspective I can pass a reference type by value or by reference, this is also true to value types
我已经写了noddie控制台应用程序,以显示我的意思..我可以做到这一点在Java中?
I have written a noddie console application to show what i mean.. can i do this in Java?
namespace ByRefByVal
{
class Program
{
static void Main(string[] args)
{
//Creating of the object
Person p1 = new Person();
p1.Name = "Dave";
PrintIfObjectIsNull(p1); //should not be null
//A copy of the Reference is made and sent to the method
PrintUserNameByValue(p1);
PrintIfObjectIsNull(p1);
//the actual reference is passed to the method
PrintUserNameByRef(ref p1); //<-- I know im passing the Reference
PrintIfObjectIsNull(p1);
Console.ReadLine();
}
private static void PrintIfObjectIsNull(Object o)
{
if (o == null)
{
Console.WriteLine("object is null");
}
else
{
Console.WriteLine("object still references something");
}
}
/// <summary>
/// this takes in a Reference type of Person, by value
/// </summary>
/// <param name="person"></param>
private static void PrintUserNameByValue(Person person)
{
Console.WriteLine(person.Name);
person = null; //<- this cannot affect the orginal reference, as it was passed in by value.
}
/// <summary>
/// this takes in a Reference type of Person, by reference
/// </summary>
/// <param name="person"></param>
private static void PrintUserNameByRef(ref Person person)
{
Console.WriteLine(person.Name);
person = null; //this has access to the orginonal reference, allowing us to alter it, either make it point to a different object or to nothing.
}
}
class Person
{
public string Name { get; set; }
}
}
如果它Java可以不这样做,那么它只是按值传递一个引用类型? (是公平地说)
If it java cannot do this, then its just passing a reference type by value? (is that fair to say)
非常感谢
骨
推荐答案
没有,爪哇不能做到这一点。 Java的只有按值传递。它通过值太大传递引用。
No, Java cannot do this. Java only passes by value. It passes references by value too.
这篇关于您可以通过Java的引用传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!