I overwrite the variables 'arr[1]' and 'test' in setValues() function.
arr[1] is changed to 'BBB'
but test doesn't change to '222'
Output: BBB111
but it should be BBB222
Why string test doesn't get updated?
public class Program
{
static void Main(string[] args)
{
string[] arr = new string[10];
arr[1] = "AAA";
string test = "111";
setValues(arr, test);
int exit = -1;
while (exit < 0)
{
for (int i = 0; i < arr.Length; i++)
{
if (!String.IsNullOrEmpty(arr[i]))
{
Console.WriteLine(arr[i] + test);
}
}
}
}
private static void setValues(string[] arr, string test)
{
arr[1] = "BBB";
test = "222";
}
}
You need to pass that string by reference to be able to modify it in a method, you can do this by adding the ref
keyword:
public class Program
{
static void Main(string[] args)
{
string[] arr = new string[10];
arr[1] = "AAA";
string test = "111";
setValues(arr, ref test);
int exit = -1;
while (exit < 0)
{
for (int i = 0; i < arr.Length; i++)
{
if (!String.IsNullOrEmpty(arr[i]))
{
Console.WriteLine(arr[i] + test);
}
}
}
}
private static void setValues(string[] arr, ref string test)
{
arr[1] = "BBB";
test = "222";
}
}
You are only altering the local reference to test
in your setValues
function. You would need to pass this variable by reference ( ref
)
private static void setValues(string[] arr, ref string test)
{
arr[1] = "BBB";
test = "222";
}
then call it like this:
setValues(arr, ref test);
这是因为setValues
方法中的test
未标记为ref
因此仅在方法内部进行更改,并且值不会超出范围。
Because the array as object is passed by reference while the string is passed by value. So, the function setValues() update the local copy of test, invisible to the caller, while update the ONLY instance of string[] arr, visible either to the caller than to the callee.
Paolo
The reason is variable scope. The variables referenced in your SetValues() method aren't the same variables referenced in Main. There are 2 ways to resolve this, based on the need of the class:
private static void setValues(string[] arr, ref string test) { arr[1] = "BBB"; test = "222"; }
public class Program { static string[] arr = new string[10]; static string test = "111"; static void Main(string[] args) { arr[1] = "AAA";
and then call it by reference as well:
SetValues(arr, ref test);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.