很抱歉,如果这听起来像一个新手的问题,但有一天,一个Java开发者关于通过引用传递一个放慢参数(通过其被换货只是传递一个参考对象)你可以在Java中通过引用传递吗?
从C#角度来看,我可以通过一个参考提到按值或通过引用类型,这也是值类型
我写了一个noddie控制台应用程序来显示我的意思..我可以在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; }
}
}
如果它不能做到这一点,那么它只是通过值传递引用类型? (是公平地说)
非常感谢
骨头
无尽的C#区别甚至不存在于Java中。 Java中的“引用类型”是什么?非原始类型?你不能按值传递非原始类型 - 它们总是引用。由于这些概念并没有真正在语言之间进行映射,所以您究竟在问什么? – 2009-11-17 12:22:35
您当然可以按值传递非原始类型。事实上,这就是所有的Java。 Java中的所有东西都是原语和引用,并且都是按值传递的。 – 2009-11-17 12:23:57
从你的例子中,我真的很高兴Java不支持这个。这会打开Java中不会发生的各种问题。 – 2009-11-17 20:06:29