Bool在当前上下文中不存在,但以与其他变量相同的方式声明

时间:2017-02-27 10:29:18

标签: c#

我有一个bool,编译器说在当前作用域中不存在,但是所有其他变量都以相同的位置/方式声明和使用。下面的代码,一些类名更改和代码简化,但结构保持不变。

iDReq does not exist in the current context

if (button.Click) {
    string sourceFileName = "";
    string destPathFileName = "";
    int exportCount = 0;
    bool iDReq = true;
    iDReq = (System.Windows.Forms.MessageBox.Show("Include ID in file names?", "ID",MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes); 
    foreach (KeyValueCollection item in SearchControl.SelectedItems)
    {
        Class.Document doc = Class.Document.GetDocument((long)item["id"].Value);
        {
            sourceFileName = @"\\server\share" + @"\" + Convert.ToString(doc.GetExtraInfo("docFileName"));
            string fileExtension = System.IO.Path.GetExtension(sourceFileName);     
            //Line below is the one that the compiler does not like.                                
            iDReq = true ? destPathFileName = destPath + @"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPathFileName = destPath + @"" + doc.Description + fileExtension;
                try {
                    System.IO.Directory.CreateDirectory(destPath);
                    System.IO.File.Copy(sourceFileName,destPathFileName,true); 
                    System.Windows.Forms.Clipboard.SetText(destPathFileName);
                    exportCount ++;
                }
                catch(Exception ex)
                {
                    ErrorBox.Show(ex); 
                }
        }
    }
}

是因为它是一个布尔值还是我错过了其他东西?

2 个答案:

答案 0 :(得分:1)

我认为你的三元写得不好,但我不确定你想要什么。我会把它重写为普通的if/else。我喜欢三元运算符,但它只是糖。

我认为你正在寻找这个:

destPathFileName = iDReq == true
    ? (destPath + @"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension)
    : (destPath + @"" + doc.Description + fileExtension);

iDReq == true是超级的。

你也可以写:

destPathFileName = destPath + @"" + doc.Description
    + (iDReq ? " (" + doc.ID + ")" : string.Empty)
    + fileExtension;
顺便说一下,@""string.Empty

并使用字符串插值:

destPathFileName = destPath + doc.Description
    + (iDReq ? $" ({doc.ID})" : string.Empty)
    + fileExtension;

答案 1 :(得分:1)

试试这个:

destPathFileName  = iDReq ? destPath + @"" + doc.Description + " " + "(" + doc.ID + ")" + fileExtension : destPath + @"" + doc.Description + fileExtension;