我想通过Unity学习C#,我想知道C#在传递参数或返回值的按引用或按值传递时是否具有与Java相同的语义?
我在C#语言中看到,您可以使用它ref来指示某些东西是通过引用传递的,这是否意味着默认情况下它是通过值传递的?
默认情况下,除非引用是原始类型,否则Java默认通过引用传递(即,不从扩展的东西Object)
这包括Java中的数组。但是我不确定C#。
对于原始类型和非原始类型,Java总是按值传递。
例如,
void JavaMethod(int i, Foo f)
{
i = 9; //not changed from caller's point of view
f = new Foo(); //not changed from caller's point of view
}
Run Code Online (Sandbox Code Playgroud)
C# is pass-by-value unless the 'ref' keyword is used:
void CSharpMethod(int i, Foo f, ref int j, ref Bar b)
{
i = 9; //not changed from caller's point of view
f = new Foo(); //not changed from caller's point of view
j = 9; //changed from caller's point of view
b = new Bar(); //changed from caller's point of view
}
Run Code Online (Sandbox Code Playgroud)
In both languages, you can modify the internal state of an non-primitive object when it is passed by value:
void JavaOrCSharpMethod(Foo f)
{
f.field = 9; //internal state is changed from caller's point of view
}
Run Code Online (Sandbox Code Playgroud)
Keep in mind the difference between assigning a new instance to a parameter and modifying the internal state of the object. Not understanding this is the source of a lot of confusion about this subject.
Also, there is no real substance in whether a primitive type or non-primitive type is used, other than the fact that primitive types do not have members which change their state, so it's always done via assignment. Any non-primitive type where state can only be changed via assignment would seem the same.
I would include some C++ examples also, but this would drastically complicate the discussion since C++ has many ways of implementing pass-by-reference.