带双qoutes的字符串

时间:2017-05-22 21:46:24

标签: c# asp.net xml

我需要将带双引号的字符串作为参数传递给代理方法,如下所示:

A = {<M> | M is a TM and L(M) contains exactly n strings }
B = {<N> | N is a TM and L(N) contains more than n strings }

从配置文件中读取这些参数值。

public void CallProxyMethod()
{
   //SomeProxyClass derives from Systems.Collections.Generic.List<string>
   var parameters = new SomeProxyClass() {"parameter1", "paramter2", "parameter3"};
   SomeProxyMethod(parameters);
}

我尝试用逗号分割配置值并为它们添加双引号,但我最终在上面的 SomeProxyClass 中得到以下值:

“\”parameter1 \“”,“\”paramter2 \“”,“\”parameter3 \“”。

我在课堂上需要的值是:

“parameter1”,“paramter2”,“parameter3”。

如何将“parameter1,parameter2,parameter3”转换为 C#中的“parameter1”,“paramter2”,“parameter3”

3 个答案:

答案 0 :(得分:1)

这样的事情应该有用......

var items = "item1, item2, item3";
var newItems = "\"" + string.join("\",\"", items.split({","})) + "\"";

答案 1 :(得分:0)

你可以用这个来实现它:

var yourString = "parameter1, parameter2, parameter3";
var result = $"\"{yourString.Replace(",",@"","")}\"";

答案 2 :(得分:0)

尝试改为使用StringBuilder

static class Quotes
{
    public static StringBuilder DoubleQuotes(params string[] parameters)
    {
        char quote = '\u0022';
        string value = null;

        for (int i = 0; i < parameters.Length; i++)
        {
        parameters[i] = 
            parameters[i]
                .Insert(0, quote.ToString()) 
                .Insert(parameters[i].Length + 1, quote.ToString());

            value += parameters[i];         
        }

    value = String.Join(", ", parameters);
    StringBuilder builder = new StringBuilder(value);

    return builder;
}

在这种情况下,您必须从List<string>更改为List<StringBuilder>。我希望这有帮助。

public void CallProxyMethod()
{
    var withHelperMethod = new SomeProxyClass()
    {
        Quotes.DoubleQuotes("parameter1", "parameter2"),
        Quotes.DoubleQuotes("parameter3")
    };

    var withoutHelperMethod = new SomeProxyClass()
    {
        new StringBuilder("\"parameter1\""),
        new StringBuilder("\"parameter2\""),
    };

    SomeProxyMethod(withHelperMethod);
    SomeProxyMethod(withoutHelperMethod);
}

This is the result what I got