对象中的动态变量

时间:2017-03-10 18:01:27

标签: c# string

假设我有一个大部分完整的字符串。在它的中间是一个可变的条目 - 例如:

string speech = @"I am very" 可变 "and I need some lighter clothes"

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

我的伪理论会是这样的:

string speech = @"I am very " + &antonym + " and I need some lighter clothes";
public string putTheSentenceTogether(string antonym)
{
    return speech(antonym);
}

可以用C#完成吗?或者其他任何方式都不需要我将speech分开?

3 个答案:

答案 0 :(得分:4)

你怎么做

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中,即VS 2015及更高版本)

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

答案 1 :(得分:4)

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

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

答案 2 :(得分:2)

这将使用字符串插值:

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

或使用string.Format

public string putTheSentenceTogether(string antonym)
{
    return string.Format("I am very {0} and I need some lighter clothes", antonym);
}

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

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

public string putTheSentenceTogether(string antonym)
{
    return string.Format(speech, antonym);
}
相关问题