也许这个问题听起来不太好或太简单了。但在这种情况下不适合我。
我的问题是: 我为字符串创建了一个扩展,比如
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;
}
我个人认为 ref
和 out
参数是一种代码味道,它通常意味着该方法负责不止一件事,或者正在做一些它不应该做的事情。在您的示例中,赋值比调用方法更具可读性。
关于c# - 字符串的扩展在 C# 中返回该字符串的意外值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11290841/