也许问题听起来不好或太简单。但在这种情况下不适合我。
我的问题是: 我为字符串创建了一个扩展名,比如
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
...
我的错误在哪里?
答案 0 :(得分:3)
这不可能作为扩展方法。对类变量的引用按值传递,为了将新值赋给方法中传递的值,您需要使用ref
参数:
public void SetString(ref string aString, string anotherString)
{
aString = anotherString;
}
我个人认为ref
和out
参数是代码气味,它通常意味着该方法不仅仅是一件事,或者是在不应该做的事情上。在您的示例中,赋值比调用方法更具可读性。
答案 1 :(得分:2)
您还可以查看我的文章:Extension Methods,其中我谈到了字符串加密扩展方法
您需要从将为您完成工作的函数返回值..
public static string SetString( this string aString, string anotherString)
{
return anotherString ;
}
string anExistingString = "123";
anExistingString = anExistingString.SetString("Other value");
答案 2 :(得分:0)
当调用一个会改变原始值的函数时.net中的默认行为是返回值并重新赋值(例如,substring不会改变值,但返回更改的值) 。 (现在你可以使用带有 ref 参数的静态过程,但是使用扩展方法是不可能的)
public static string SetString( this string aString, string anotherString ) {
//process logic here
return anotherSTring;
}
//call
string anExistingString = "123";
anExistingString = anExistingString.SetString("Other value");
答案 3 :(得分:0)
您可以尝试调用String.Copy
方法:
public static void SetString(this string aString, string anotherString )
{
aString = string.Copy(anotherString);
}