範囲についての質問です。
基本的に、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)
、データが正しくクエリされたかどうかを知ることができます。