C# 中的string
类型是引用类型,按值传递引用类型参数会复制引用,因此我不需要使用ref
修饰符.但是,我需要使用 ref
修饰符来修改输入的 string
。这是为什么?
using System;
class TestIt
{
static void Function(ref string input)
{
input = "modified";
}
static void Function2(int[] val) // Don't need ref for reference type
{
val[0] = 100;
}
static void Main()
{
string input = "original";
Console.WriteLine(input);
Function(ref input); // Need ref to modify the input
Console.WriteLine(input);
int[] val = new int[10];
val[0] = 1;
Function2(val);
Console.WriteLine(val[0]);
}
}
最佳答案
您需要引用字符串参数的原因是,即使您传入了对字符串对象的引用,为参数分配其他内容也只会替换当前存储在参数变量中的引用.换句话说,你改变了参数所指的内容,但原始对象没有改变。
当您引用参数时,您已经告诉函数该参数实际上是传入变量的别名,因此分配给它会产生预期的效果。
编辑:请注意,虽然字符串是不可变的引用类型,但它在这里并不太相关。由于您只是试图分配一个新对象(在本例中为字符串对象“已修改”),因此您的方法不适用于任何 引用类型。例如,考虑一下对您的代码的这种轻微修改:
using System;
class TestIt
{
static void Function(ref string input)
{
input = "modified";
}
static void Function2(int[] val) // don't need ref for reference type
{
val = new int[10]; // Change: create and assign a new array to the parameter variable
val[0] = 100;
}
static void Main()
{
string input = "original";
Console.WriteLine(input);
Function(ref input); // need ref to modify the input
Console.WriteLine(input);
int[] val = new int[10];
val[0] = 1;
Function2(val);
Console.WriteLine(val[0]); // This line still prints 1, not 100!
}
}
现在,数组测试“失败”了,因为您要将一个新对象分配给非引用参数变量。
关于c# - 在 C# 函数中键入 'string' 作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6166178/