3

我们假设例如我有一个字符串,我想转义它,并且阅读得很好)

需要一个工作扩展什么可以解决这个问题

我试过了。

var t = "'";
t.Escape();// == "%27" (what i need), but it not assign result to var. t
t = t.Escape();//works, but ugly.

和扩展

public static string Escape(this string string_2)
    {
        if (string_2.HasValue())
            string_2 = Uri.EscapeDataString(string_2);
        return string_2;
    }

如何修复这个扩展工作?

4

2 回答 2

5

t = t.Escape();是 .NET 中用于更改字符串的常用习语。例如t = t.Replace("a", "b");,我建议您使用它。这是必要的,因为字符串是不可变的

有一些方法可以解决它,但它们比 IMO 更丑。例如,您可以使用ref参数(但不能在扩展方法上):

public static string Escape (ref string string_2) { ... }
Util.Escape(ref t);

或者,您可以创建自己的可变类 String 类:

public class MutableString { /** include implicit conversions to/from string */ }
public static string Escape (this MutableString string_2) { ... }

MutableString t = "'";
t.Escape();

我要提醒您,如果您使用除t = t.Escape();.

于 2013-06-07T11:56:28.927 回答
1

"Mutable string" in C# is spelled StringBuilder.

So you could do something like this:

public static void Escape(this StringBuilder text)
{
    var s = text.ToString();
    text.Clear();
    text.Append(Uri.EscapeDataString(s));
}        

But using it wouldn't really be that great:

StringBuilder test = new StringBuilder("'");
test.Escape();
Console.WriteLine(test);

The real answer is to use the "ugly" string reassignment

t = t.Escape();//works, but ugly.

You'll get used to it. :)

于 2013-06-07T12:25:27.117 回答