C# 对象中的动态变量

C# 对象中的动态变量,c#,string,C#,String,假设我有一个基本完整的字符串。中间是一个可变的条目,例如: 我非常变化无常,我需要一些较轻的衣服 假设我不想创建另一个字符串来处理那个句子的最后一部分,我该如何将hot的许多单词中的一个替换为variable 我的伪理论是这样的: string speech = @"I am very " + &antonym + " and I need some lighter clothes"; public string putTheSentenceTogether(string antonym

假设我有一个基本完整的字符串。中间是一个可变的条目,例如:

我非常变化无常,我需要一些较轻的衣服

假设我不想创建另一个字符串来处理那个句子的最后一部分,我该如何将hot的许多单词中的一个替换为variable

我的伪理论是这样的:

string speech = @"I am very " + &antonym + " and I need some lighter clothes";
public string putTheSentenceTogether(string antonym)
{
    return speech(antonym);
}
这可以用C语言完成吗?或者其他不需要我分开演讲的方式?

你呢

string speech = @"I am very {0} and I need some lighter clothes";
public string PutTheSentenceTogether(string antonym)
{
    return string.Format(speech, antonym);
}
或者你也可以在C 6.0中,即与2015年及更高版本相比

public string PutTheSentenceTogether(string antonym)
{
    return $"I am very {antonym} and I need some lighter clothes";
}

使用C 6.0或更高版本,请尝试:

string myAntonym = "hot";
string speech = $"I am very {myAntonym} and I need some lighter clothes";

这将通过使用字符串插值来实现:

public string putTheSentenceTogether(string antonym)
{
    return $"I am very {antonym} and I need some lighter clothes";
}
或者使用string.Format

如果要在方法之外声明字符串,可以执行以下操作

string speech = "I am very {0} and I need some lighter clothes";

public string putTheSentenceTogether(string antonym)
{
    return string.Format(speech, antonym);
}

你试过了吗?在c中连接字符串的方法有很多种。第一个例子中的插值需要用“$”符号代替“@”符号。虽然所有这些例子都可以工作,但我认为这是最干净、最短的,因此我选择它作为最合适的答案。
string speech = "I am very {0} and I need some lighter clothes";

public string putTheSentenceTogether(string antonym)
{
    return string.Format(speech, antonym);
}