C# - 如何声明一个将由if语句中的数据库调用填充的变量?

时间:2012-11-05 20:26:52

标签: c# webmatrix

我希望从if语句中的数据库调用中获取数据,然后我希望能够在页面后面的if语句之外使用该数据。

那么,为什么这不起作用?我该怎么做才能使这项工作成功?我只是收到错误消息“编译器错误消息:CS0103:名称'selectedData'在当前上下文中不存在”。我试图在if语句之外声明一个“selectedData”变量,以便它可用,但我似乎无法弄清楚如何正确地做到这一点。

@{

    var testVariable = "blah";

    //set cache key and query based their being a craft name
    if(testVariable.Length > 0){

        var db = Database.Open("Connection"); 
        var selectedData = db.Query("SELECT * FROM Products");             
    } 

}


<div>
    @foreach (var row in selectedData){
        @row.ContentTitle <br />
        @row.ContentShortDescription <br />
    } 
</div>

2 个答案:

答案 0 :(得分:2)

这是一个范围问题。您需要在if范围之外声明您的变量。

@{

    var testVariable = "blah";
    Type selectedData;

    //set cache key and query based their being a craft name
    if(testVariable.Length > 0){

        var db = Database.Open("Connection"); 
        selectedData = db.Query("SELECT * FROM Products");             
    } 

}


<div>
    @foreach (var row in selectedData){
        @row.ContentTitle <br />
        @row.ContentShortDescription <br />
    } 
</div>

我不熟悉这里的类型,所以我使用Type。在那里替换适当的类型。请注意,此代码段也不确保在进入循环之前正确设置selectedData。你也应该处理它。

答案 1 :(得分:0)

这是关于范围的问题。

基本上,在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)知道数据是否已正确查询。