使用扩展方法修改字符串实例变量

Modifying string instance variable with extension method

我正在尝试为字符串 class 创建一个简单的扩展方法,这将允许我提供要附加到包含换行符的现有字符串变量的文本:

string myStr = "Line 1";
myStr.AppendLine("Line 2");

此代码应产生如下打印的字符串

Line 1
Line 2

这是我为它编写的代码:

public static class StringExtensions
{
    public static void appendLine(this String str, string text)
    {
        str = str + text + Environment.NewLine;
    }
}

但是当我调用代码时,新文本永远不会附加到原始实例变量。如何实现?

字符串是不可变的。您的扩展方法会创建一个新字符串,而不是更改传入的字符串。您需要将其写为:

public static String AppendLine(this String str, string text)
{
    return str + text + Environment.NewLine;
}

并这样称呼它:

string myStr = "Line 1";
myStr = myStr.AppendLine("Line 2");

您需要修改变量的值才能使其正常工作,因为字符串是不可变的(参见 public C# string replace does not work)。不幸的是,无法使用扩展方法来做到这一点,因为那里不允许 ref

 public static void appendLine(this ref String str, string text) // invalid

所以你的选择

  • 常规方法 ref

      public static void AppendLine(ref String str, string text)
      {
         str = str + text;
      }
    
  • return 来自扩展方法的新值:

      public static string AppendLine(this String str, string text)
      {
         return str + text;
      }
    

注意:考虑 StringBuilder 是否更适合您的情况。

您必须 return 其他人之前提到的来自扩展方法的值。您还可以使用新的 C# 表达式语法,如下所示 return 值。

public static string appendLine(this String str, string text) => str + text + Environment.NewLine;

这与带有 return 语句的方法的作用相同。但是,我觉得它很优雅。