如何在 C# 中的 if 语句之外传递字符串变量值?



我是编程新手,我想将字符串变量"serverPath"的值传递给字符串变量"DestinationPath"。 但是,我遇到此错误"使用未分配的变量"。 这是我的代码:

string DestinationPath;
string serverPath;
if (ServerList.SelectedItem.Value == "1")
{
serverPath = "10..13.58.17";
}
else if (ServerList.SelectedItem.Value == "2")
{
serverPath = "10..13.58.33";
}
DestinationPath = @"\"+serverPath+"C$TEST FOLDERDESTINATION FOLDER";

我在这里做错了什么? 如何将 serverPath 的值传递到 If 语句之外?任何帮助将不胜感激。谢谢。

使用if语句,您可以查找两种不同条件之一并相应地设置 serverPath。 但是在您的代码中,这些条件可能都不满足,并且根本不会设置变量。 这就是您收到错误的原因。

解决方案为以下任一:

如果您确定只有"1"或"2",请将第二个else if更改为仅else

if (ServerList.SelectedItem.Value == "1")
{
serverPath = "10..13.58.17";
}
else
{  
//Must be "2"
serverPath = "10..13.58.33";
}

或添加其他默认案例

if (ServerList.SelectedItem.Value == "1")
{
serverPath = "10..13.58.17";
}
else if (ServerList.SelectedItem.Value == "2")
{
serverPath = "10..13.58.33";
}
else
{
serverPath = "10..99.99.99";
}

或者,您需要在声明变量时设置默认值(或空(。

string serverPath = "";  //Please note, this can still lead to bugs in your code!

string serverPath = "10..99.99.99";

在 C# 中,变量在使用之前必须对其进行初始化

首先你做

string serverPath = string.Empty;

毕竟你的所有条件

if(!string.IsNullOrEmpty(serverPath))
{
DestinationPath = @"\"+serverPath+"C$TEST FOLDERDESTINATION FOLDER";
}

将变量赋值为

string DestinationPath = string.Empty;
string serverPath = string.Empty;

希望,这行得通。

而不是使用if-else-if您可以使用switch语句

最新更新