c# - 在 C# 函数中键入 'string' 作为参数

标签 c# .net string ref

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/

相关文章:

javascript - 使用 jQuery 在网页上突出显示字符串的字符

python - python 中的字符串连接发生在下一行

c# - 轨迹渲染器在传送时留下轨迹

c# - 重置DataGrid排序回到其初始状态

.net - 具有多种文化的MVC十进制分隔符

c# - 如何从动态 C# 代码编译中获取错误信息

java - 查询不返回任何数据 SQLite

c# - 如何在 C# 中注入(inject)类(不是接口(interface))?

c# - 如何从 Windows Phone 8.1 发现蓝牙低功耗设备 (BLE)

c# - 根据受欢迎程度选择项目 : Avoiding a glorified sort