简体   繁体   English

C#一起添加字符串

[英]C# Add strings together

im making a speech alias program. 我正在制作语音别名程序。 Im trying to make it to add commands. 我试图使其添加命令。 You know basically to make a array of strings you do string mystring = "string1","string2"; 您基本上知道要制作一个字符串数组,您可以执行以下操作:string mystring =“ string1”,“ string2”; How am I able to add it just like ,"string3" to make it string mystring = "string1","string2","string3"; 我怎样才能像“,string3”那样添加它,使其成为字符串mystring =“ string1”,“ string2”,“ string3”; Here is my code: 这是我的代码:

List<string> myCollection = new List<string>();
            myCollection.Add("hello");
            myCollection.Add("test");
            string final = string.Join(",", myCollection.ToArray());
            richTextBox1.AppendText(final);
            sp.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(new String[] { "" + final }))));

The API you are calling requires an array of string . 您正在调用的API需要一个string数组。 If you know how many strings you will be passing, then do not use a List<string> . 如果您知道要传递多少个字符串,请不要使用List<string> This will help you avoid having to convert List<string> to a string[] . 这将帮助您避免将List<string>转换为string[] This is how it will work: 它是这样工作的:

var myCollection = new string[2];
myCollection[0] = "hello";
myCollection[1] = "test";
sp.LoadGrammar(new Grammar(new GrammarBuilder(myCollection)));

If you are not sure how many strings you will be passing then use a List<string> like this: 如果不确定要传递多少个字符串,请使用List<string>像这样:

var myCollection = new List<string>();
myCollection.Add("hello");
myCollection.Add("test");

Then you need to convert a List<string> to a string[] , just call ToArray<string>() on your collection like this: 然后,您需要将List<string>转换为string[] ,只需像这样在集合上调用ToArray<string>()

var myCollectionAsArray = myCollection.ToArray();
sp.LoadGrammar(new Grammar(new GrammarBuilder(new Choices(myCollectionAsArray))));

What do you mean by if you know how many strings you will be passing? 如果您知道要传递多少个字符串,那意味着什么?

If you were checking some dynamic condition (a condition only known at runtime) to add items to the choices collection, then you will need a List<string> . 如果要检查一些动态条件(仅在运行时才知道的条件)以将项目添加到options集合,那么您将需要List<string> For example: 例如:

var myCollection = new List<string>();

myCollection.Add("hello");
if (someCondition)
{
    // this will only be known at runtime
    myCollection.Add("test");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM