簡體   English   中英

“新表達式在類型后需要(),[]或{}”是什么意思?

[英]What does “A new expression requires (), [], or {} after type” mean?

這是我的代碼:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Data;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=OCS-MXL930055N\\;Initial           Catalog=sample;Integrated Security=True";
        SqlCommand cmd = new SqlCommand

        con.Open("Select * from ShoppingList", con);

        con.Close("Select * from ShoppingList", con);
    }
}

這些是我遇到的問題:

con.Open("Select * from ShoppingList", con)();

con.Close("Select * from ShoppingList", con)();

有什么幫助嗎? 我不太確定自己在做什么錯。

您的聲明:

SqlCommand cmd = new SqlCommand

應該 :

SqlCommand cmd = new SqlCommand("Select * from ShoppingList");

稍后在打開和關閉連接時,只需刪除參數,這些參數對於SqlCommand構造函數是必需的。

您可能會有類似以下的代碼:

using(SqlConnection con = new SqlConnection("Data Source=OCS-MXL930055N\\;Initial Catalog=sample;Integrated Security=True"))
using(SqlCommand cmd = new SqlCommand("Select * from ShoppingList", con))
{
    //.. code to execute command
}

在MSDN上閱讀有關基本C#,構造函數和ADO.Net示例的信息。

C#不是紅寶石,您需要表明您的意圖。 實例化對象有3種方式,所有方式都使用new運算符:

var myObj = new MyObj(); // call a constructor (parameterless)
var myObjArray = new MyObj[10]; // create an array of 10 MyObjs
var myObj = new MyObj{someProperty="someValue"}; // initializer notation.

請注意,您可以混合使用數組和初始化程序,以便執行此操作及其合法性:

var myInts = new int[]{1,2,3,4,5,6}; //create an int array with 6 values.

要修復您的代碼段,您需要添加括號,如下所示:

   SqlCommand cmd = new SqlCommand();

如果要發送sql字符串,我強烈建議使用nuget上的Dapper-Dot-Net庫。

您尚未正確創建SqlCommand實例:

SqlCommand cmd = new SqlCommand

變成:

SqlCommand cmd = new SqlCommand("Select * from ShoppingList");

這又意味着:

con.Open("Select * from ShoppingList", con)();

變得簡單:

con.Open();

con.Close();類似con.Close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM