c# - 在方法中更改引用类型(字符串)

标签 c# oop

我正在将一个字符串变量传递给一个方法。我知道字符串是引用类型,但我在方法中分配的值丢失了。

public static void TestMethod(string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}

无论如何,这不会发生在数组中。有人可以解释为什么可能是原因吗?

最佳答案

因为 myString = "world" 为参数分配了一个新字符串,而不是更新现有字符串。要更新对字符串的原始引用,您必须使用 ref 传递参数。

public static void TestMethod(ref string myString)
{
    myString = "world";
}

static void Main(string[] args)
{
    string s = "hello";
    Console.WriteLine(s); // output is "hello"
    TestMethod(ref s);
    Console.WriteLine(s); // output is also "hello" not "world" !?
}

关于c# - 在方法中更改引用类型(字符串),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4317302/

相关文章:

c# - 如何从 facebook 登录 API 获取手机号码?

c# - 在 ASP.Net Core 中验证 IFormFile 的图像类型

c# - Tab 控件中的文本换行

php - 为什么要为 doctrine2 类使用 getter setter

c++ - 如何 dynamic_cast 一个没有虚方法的类的指针?

java - 将实例变量设为私有(private)只会对子类有利吗?

c++ - FLTK 填充多边形

c# - 在 ServerControl (ASP.NET) 的 <Head .../> 标记内添加 <Script .../> 标记?

c++ - 如何将指针传递给构造函数?

c# - 当前使用 C# 3.0 和 WinForms 在 .NET 3.5 中进行数据绑定(bind)的方法