有没有一种方法可以让我在不在 switch 语句中的情况下访问变量? C#

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

我正在为我的游戏制作一个审查程序,在用安全词替换脏话后,我似乎无法访问经过审查的代码。

public string Censorship(string fText)
    {
        int i = 0; //Keep variable for checking which word is being written
        string nText = fText.ToLower();
        string cText; //Correct text
        foreach (string Word in censorWords) // Loop through text to see if it contains swear word
        {
            if (nText.Contains(Word)) //Check if the lowered text contains the swear word
            {   
                switch (i) //Replace each swear word with a safe word
                {
                    case 0: //The actual codes has the swear words there but I'm not putting it for the purpose of asking the question
                        cText = fText.Replace("f***", "flip");
                        break;
                    case 1:
                        cText = fText.Replace("c*********", "waste of air");
                        break;
                    case 2:
                        cText = fText.Replace("b****", "dude");   
                        break;
                    case 3:
                        cText = fText.Replace("a******", "jerk");
                        break;
                    case 4:
                        cText = fText.Replace("b*******", "nonsense");
                        break;
                    case 5:
                        cText = fText.Replace("s*************", "douchebag");
                        break;
                    default:
                        break;
                }
            }
            i++; // increment i
        }
        return cText; //Return correct text
    }

我希望能够访问

cText
,但我没有,所以我需要有关如何做到这一点的帮助。它只是给出了一个错误说

使用未分配的局部变量'cText'CS0165

我是初学者,所以如果这是一个愚蠢的问题,我深表歉意。

c# string variables replace switch-statement
1个回答
0
投票

是的。有一种方法。您有正确的代码。错误与您的问题无关。您可以像 cText = string.Empty; 那样初始化 cText 变量

© www.soinside.com 2019 - 2024. All rights reserved.