【问题标题】:Asp.net, Linq Error: 'int' is a 'type' but is used like a 'variable'Asp.net,Linq 错误:“int”是“类型”,但用作“变量”
【发布时间】:2025-12-09 02:55:01
【问题描述】:

我正在使用 asp.net 和链接来显示数据库中的一组书籍。 n 它给了我一个错误

Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.

Compiler Error Message: CS0118: 'int' is a 'type' but is used like a 'variable'

Source Error:

Line 48:         using(MobileBooksDataContext categoryList = new MobileBooksDataContext())
Line 49:         {
Line 50:             int catID = Int32(CategoryName.SelectedItem); 
Line 51:             var newBookList = from b in categoryList.team5_bookmobiles
Line 52:                               where(b.ca_id == catID)


protected void getBookList()
    {

        using(MobileBooksDataContext categoryList = new MobileBooksDataContext())
        {
            int catID = Int32(CategoryName.SelectedItem); 
            var newBookList = from b in categoryList.team5_bookmobiles
                              where(b.ca_id == catID)
                            select new
                            {
                                lblBook_name = b.book_name,
                                lblBook_author = b.book_author,
                                lblBook_shortdesc = b.book_short_desc
                            };

            lv_Books.DataSource = newBookList;
            lv_Books.DataBind();
        }
    }

    protected void btn_Select_Click(object sender, EventArgs e)
    {
        getBookList();
    }

我从下拉列表中获取类别 ID,并将其与不同表中书籍的类别 ID 进行匹配。

【问题讨论】:

    标签: .net asp.net linq ado.net


    【解决方案1】:

    我认为应该是:

    int catID = Int32.Parse(CategoryName.SelectedValue.ToString()); 
    

    【讨论】:

    • ToString() 不是必需的,SelectedValue 已经是一个字符串。
    • 哦,谢谢!不知道。我想添加 ToString() 无论如何都不会造成伤害。
    【解决方案2】:

    如果你改变了怎么办

    int catID = Int32(CategoryName.SelectedItem); 
    

    int catID = Int32.Parse(CategoryName.SelectedItem); 
    

    【讨论】:

    • 'int.Parse(string)' 的最佳重载方法匹配有一些无效参数这是它给出的错误。
    【解决方案3】:

    第 50 行像函数一样使用 Int32 构造函数。将Int32(CategoryName.SelectedItem) 更改为new Int32(CategoryName.SelectedItem),或者使用(Int32)(CategoryName.SelectedItem) 转换为int。

    【讨论】:

      【解决方案4】:

      只是为了安全起见:

      int catID = Int32.Parse(CategoryName.SelectedItem.ToString());
      

      【讨论】:

        【解决方案5】:

        如果您使用 DataBinding,SelectedItem 很可能是被数据绑定的对象。你可以使用它,但你必须先施放它。这可能会提高性能,因为您不必执行字符串解析来获取您的类别 ID。

        或者,您可以使用属性 DropDownList.SelectedValue,您可能已经使用数据绑定向导配置了该属性,或者使用控件声明中的属性 DataValueField。

        无论哪种方式,您都不能使用类似 C++ 或 VB 的语法使用 C# 执行转换为 Int32。

        如果您使用 SelectedValue 属性,您将拥有一个字符串并将其转换为 Int32,您必须编写如下内容:

        var value = Int32.Parse(CategoryName.SelectedValue, CultureInfo.InvariantCulture);
        

        【讨论】:

          最近更新 更多