Cannot convert method group 'Read' to non-delegate type 'bool'

雨燕双飞 提交于 2019-12-08 17:19:08

问题


I am trying to use SqlDataReader to check if a entry exists. If it exists, it will return the ID, else it will return false. When I try to compile, I'm getting the error "Cannot convert method group 'Read' to non-delegate type 'bool'. I have been following an example I found in VB, but it seems the translation may not be correct.

private string checkProfileExists()
{
    string strReturn = "False";
    string strSql = ("SELECT ID FROM tblInformation WHERE txtUsername=@UserName " + 
        "AND TrackingID=@TrackingID");
    string strConn = ConfigurationManager.ConnectionStrings["WEM_PassWord_Reset"].
        ConnectionString;


    SqlConnection objConn = new SqlConnection(strConn);
    SqlCommand objCmd = new SqlCommand(strSql, objConn);

    objCmd.Parameters.AddWithValue("@Username", txtUsername.Text);
    objCmd.Parameters.AddWithValue("@TrackingID", txtTrackingID.Text);

    try
    {
        objConn.Open();
        System.Data.SqlClient.SqlDataReader rdr = objCmd.ExecuteReader();

        if (rdr.Read)
        {
            strReturn = rdr("ID").ToString;
        }
        else
        {
            strReturn = "False";
        }
    }
    catch (Exception ex)
    {
        lblErrorMessage.Text = ex.ToString();
    }
    finally
    {
        objConn.Close();
        objCmd = null;
    }

    return strReturn;
}

回答1:


When you see the phrase 'method group' in a C# error, one explanation to consider is that you have omitted the parentheses () from a method that takes no arguments. In this case, the method is Read on your DataReader.

When the compiler sees Read (with no parentheses), it thinks you are talking about the method itself, as if trying to assign it to a delegate, say. Whereas what you actually want to do is invoke the method - to do this, in C#, you must give the list of arguments (which in this case is empty), thus: Read().




回答2:


if (rdr.Read())
{
    strReturn = rdr["ID"].ToString();
}



回答3:


The () for method invocation of parameterless methods are not optional in C#. Without the parentheses the the expression identifies the method(group) and not its result value. This behavior makes the grammar much less ambiguous, especially for methods that return delegates.

The first reaction of a C# programmer when he sees "Cannot convert method group '...' to non-delegate type '...'" is usually "Oh I forgot my () for invocation".




回答4:


Seeing your source I highly recommend to use the using statement for both the SqlConnection AND the SqlDataReader.

If you do NOT Close the reader, the garbagecollection moment will decide when the reader finalizes. You can bring SqlServer DOWN when you do not know that.



来源:https://stackoverflow.com/questions/4890323/cannot-convert-method-group-read-to-non-delegate-type-bool

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!