c# - 字符串的扩展在 C# 中返回该字符串的意外值

标签 c#

也许这个问题听起来不太好或太简单了。但在这种情况下不适合我。

我的问题是: 我为字符串创建了一个扩展,比如

public static void SetString( this string aString, string anotherString ) {

         aString = anotherString ;

         // process info for that string ... (database, files, etc)
      }

如果我这样调用该扩展程序:

string anExistingString = "123";
anExistingString.SetString("Other value");

Console.Write(anExistingString);

但返回 123 而不是 Other value...

我的错误在哪里?

最佳答案

作为扩展方法这是不可能的。对类变量的引用按值传递,为了将新值分配给方法中传递的值,您需要使用 ref 参数:

public void SetString(ref string aString, string anotherString)
{
  aString = anotherString;
}

我个人认为 refout 参数是一种代码味道,它通常意味着该方法负责不止一件事,或者正在做一些它不应该做的事情。在您的示例中,赋值比调用方法更具可读性。

关于c# - 字符串的扩展在 C# 中返回该字符串的意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11290841/

相关文章:

c# - Windows 窗体应用程序命令行参数

c# - 异步等待 vs GetAwaiter().GetResult() 和回调

c# - Mathhelper.Clamp 不精确?

c# - 使用 RenderTargetBitmap 时如何获得高质量的文本?

c# - 同一解决方案中的 MVC 和 Web API 项目

c# - 从VAR中获取值(value)

c# - 如何在不使用 List 的情况下将 Linq 查询的值传递给普通字符串?

javascript - 使用 Javascript 获取 Gridview 行中特定项目的值

c# - 如何在 Entity Framework 中查找具有组合键的实体

C# 类属性可枚举