Вопрос

I've recently explored c# to myself. But stuck with this problem.

So I have a method dbExec

public void dbExec(Action<OleDbCommand> func)
{
    using (var conn = new OleDbConnection(connStr))
    {
        conn.Open();
        var cmd = conn.CreateCommand();
        func(cmd); 
    }
}

delegate,

public delegate void DelCmd(OleDbCommand cmd);

and another method:

public ICollection<string> CheckUserPermissions() 
{
    List<string> logins = new List<string>();
    DelCmd delCmd = delegate(OleDbCommand cmd)
    {
        cmd.CommandText = "SELECT PERMISSIONS.LOGIN FROM PERMISSIONS";
        using (var rdr = cmd.ExecuteReader()) while (rdr.Read()) logins.Add(rdr["LOGIN"].ToString());  
    };
    dbExec(delcmd);
    return logins;
} 

The problem with dbExec(delcmd); statement. The error is "delcmd doesn't exist in current context". How to pass an anonymous method as a parameter to another method with Action declared parameter?

Это было полезно?

Решение

You could also avoid defining a delegate altogether.

Like this:

public ICollection<string> CheckUserPermissions()
{
    List<string> logins = new List<string>();

    Action<OleDbCommand> delCmd = cmd => 
    {
        cmd.CommandText = "SELECT PERMISSIONS.LOGIN FROM PERMISSIONS";
        using (var rdr = cmd.ExecuteReader()) 
            while (rdr.Read()) logins.Add(rdr["LOGIN"].ToString());
    };
    dbExec(delCmd);
    return logins;
}

Edit: I actually mean what Servy wrote in the comment on the other answer, but he described it way better.

Другие советы

You have a typo - it should be delCmd instead of delcmd. C# is a case-sensitive language

UPDATE: DelCmd is not same as Action<OleDbCommand> - that is different types, and you even can't cast delegates to each other. But you can create new action delegate:

dbExec(new Action<OleDbCommand>(delCmd));
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top