這是一個關於範圍的問題。
基本上,在C#中,當您打開一組新的{}
時,您聲明瞭一個新的作用域。在該範圍內創建變量,退出時會被銷燬。這是一個相當簡單的解釋,不完全準確,但它很容易理解。
{
var testVariable = "blah";
//set cache key and query based their being a craft name
if(testVariable.Length > 0)
{
var db = Database.Open("Connection");
// Create a new variable.
var selectedData = db.Query("SELECT * FROM Products");
}
// Variable doesn't exist anymore.
}
要解決這個問題:
{
var testVariable = "blah";
// Create variable outside the if scope
var selectedData = null; // Won't compile, compiler cannot find valid variable type.
//set cache key and query based their being a craft name
if(testVariable.Length > 0)
{
var db = Database.Open("Connection");
// Assign a value to a variable
selectedData = db.Query("SELECT * FROM Products");
}
// Variable still exist!
}
// Here, variable would cease to exist. :(
但在這裏,代碼將無法編譯,因爲編譯不知道是什麼類型selectedData
,因爲我在其創建爲它分配null
。所以,讓我們說selectedData
是Data
類型:
{
var testVariable = "blah";
// Create variable outside the if scope
Data selectedData = null; // Now it compiles. :)
//set cache key and query based their being a craft name
if(testVariable.Length > 0)
{
var db = Database.Open("Connection");
// Assign a value to a variable
selectedData = db.Query("SELECT * FROM Products");
}
// Variable still exist!
}
// Here, variable would cease to exist. :(
之後,你可以做if (selectedData != null)
知道,如果數據被正確查詢。
我想這確實是我的問題所在。我試着添加var selectedDate =「」;在那裏你添加了行,但然後我得到以下錯誤「編譯器錯誤消息:CS0029:不能隱式地將類型'System.Collections.Generic.IEnumerable'轉換爲'string'」。所以我想我不能使用「var」作爲類型,但是它會是什麼類型? –
user1801249
那麼這是我在帖子中提到的..使用db.Query返回的類型。我不知道那是什麼。看看文檔。 –
嘗試用'IEnumerable selectedData = null;'。 –
GmG