使用在其外部的“If/Else”循环中创建的字符串?

问题描述 投票:0回答:1

我想使用 If/Else 语句,其中设置相同的字符串值,然后在 If/Else 循环之外使用此创建的字符串。 但是,我收到错误名称“//字符串名称”在当前上下文中不存在

        bool hitBell = bellCounter == 0;
    if (hitBell)
    {
        string bell = "You just hit the bell for the first time.";
    }
    else
    {
        //The value "bellCounter" is another int variable not relevant here. It was created outside of the If/Else loop.
                string bell = $"You just hit the bell. But, you already rang it {bellCounter} times before, you are such an impatient person";

    }
    string finalMessage = $"{bell}, let's hope the auditor reacts to it.";
               //Here will be another line of code that increments the "bellCounter" by one.

这是我尝试过的,它返回了上述错误。这是否可能,如果不可能,有哪些可能的替代方案?

c#
1个回答
0
投票

以下更改可以解决您的问题吗?

bool hitBell = bellCounter == 0;
string bell = "";
if (hitBell)
{
    bell = "You just hit the bell for the first time.";
}
else
{
    //The value "bellCounter" is another int variable not relevant here. It was created outside of the If/Else loop.
    bell = $"You just hit the bell. But, you already rang it {bellCounter} times before, you are such an impatient person";

}
string finalMessage = $"{bell}, let's hope the auditor reacts to it.";
//Here will be another line of code that increments the "bellCounter" by one.
© www.soinside.com 2019 - 2024. All rights reserved.