这是一个关于范围的问题。
基本上,在 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)
知道数据是否被正确查询。