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

如何在C#中的If语句外部传递字符串变量值?,c#,string,if-statement,C#,String,If Statement,我是编程新手,我想将字符串变量“serverPath”的值传递给字符串变量“DestinationPath”。然而,我有一个错误“使用未赋值变量”。这是我的代码: string DestinationPath; string serverPath; if (ServerList.SelectedItem.Value == "1") { serverPath = "10..13.58.17";

我是编程新手,我想将字符串变量“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 FOLDER\DESTINATION FOLDER";

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

将变量指定为

     string DestinationPath = string.Empty;
     string serverPath = string.Empty;
希望,这是有效的


与使用
if-else-if
语句不同,您可以在
if
语句中使用
switch
语句,查找两种不同条件中的一种,并相应地设置服务器路径。但是在您的代码中,这些条件可能都不满足,并且根本不会设置变量。 这就是为什么会出现错误

解决方案为以下任一种:

如果您可以确定只有“1”或“2”,则将第二个
else If
更改为just
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!

在C#中,变量在使用前必须初始化

首先你需要

string serverPath = string.Empty;
在你所有的条件之后

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

您应该始终有一个
else
,并始终初始化变量您在if块之外声明了变量,因此它将在if块之外的范围内“您应该始终有一个else”-不您不应该总是有一个
else
。如果有一个空的
else
,你应该重构(最简单的方法:删除它)你的代码,而不是用不必要的结构把它弄得乱七八糟。有时C编译器会发出一条看起来模糊且难以理解的错误消息。这不是其中之一。错误消息确切地告诉您它的意思:代码中有一条语句正在使用编译器无法证明已赋值的变量。在上面的示例中,如果选中的值既不是
“1”
也不是
“2”
,则不会分配
serverPath
值。有关如何发生此错误的变化以及处理此错误的技术的更多详细信息,请参见标记的重复项。
if(!string.IsNullOrEmpty(serverPath))
{
   DestinationPath = @"\\"+serverPath+"\C$\TEST FOLDER\DESTINATION FOLDER";
}