这是一个关于范围的问题。
基本上,在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