在 C# 中使用扩展方法更改值(在 VB.NET 中允许)

Change value using Extension Method in C# (as allowed in VB.NET)

我正在尝试制作类似

的东西
string s = "Hello";
s.Clear();

然后我创建了这样的扩展方法:

public static void Clear(this string s)
{
    s = string.Empty;
}

但是,当我看到该值时,它并没有改变:

我不能使用 refout 因为它们不能与关键字 this[ 一起使用=27=]。有什么想法吗?

这是不可能的。 来自 the documentation:

Strings are immutable--the contents of a string object cannot be changed after the object is created, although the syntax makes it appear as if you can do this. For example, when you write this code, the compiler actually creates a new string object to hold the new sequence of characters, and that new object is assigned to b. The string "h" is then eligible for garbage collection.

如果您正在寻找 String 的一种 可变 版本,您可以尝试使用 StringBuilder:

   StringBuilder s = new StringBuilder("Hello");
   s.Clear();

   ...

   String myFinalString = s.ToString(); 

如果扩展方法检查条件,您可以传递一个 Action 作为参数(调用者传递 lambda 表达式),以便只有在满足条件时才执行操作。这样,除非满足条件,否则您可以避免对变量做任何事情(甚至将其设置为自身)。