C# - Passing an anonymous function as a parameter

2019-08-01 19:07发布

I'm using FluentData as an orm for my database and I'm trying to create a generic query method:

internal static T QueryObject<T>(string sql, object[] param, Func<dynamic, T> mapper)
{
    return MyDb.Sql(sql, param).QueryNoAutoMap<T>(mapper).FirstOrDefault();
}

Except in my class's function:

public class MyDbObject
{
    public int Id { get; set; }
}


public static MyDbObject mapper(dynamic row)
{
    return new MyDbObject {
    Id = row.Id
    };
}

public static MyDbObject GetDbObjectFromTable(int id)
{
    string sql = @"SELECT Id FROM MyTable WHERE Id=@Id";
    dynamic param = new {Id = id};
    return Query<MyDbObject>(sql, param, mapper); 
}

at Query<MyDbObject>(sql, param, mapper) the compilers says:

An anonymous function or method group connot be used as a constituent value of a dynamically bound object.

Anyone have an idea of what this means?

Edit:

The compiler doesn't complain when I convert the method into a delegate:

public static Func<dynamic, MyDbObject> TableToMyDbObject =
    (row) => new MyDbObject
                 {
                     Id = row.Id
                 }

It still begs the question of why one way is valid but not the other.

2条回答
Bombasti
2楼-- · 2019-08-01 19:34

The compiler doesn't complain when I convert the method into a delegate:

public static Func<dynamic, MyDbObject> TableToMyDbObject =
    (row) => new MyDbObject
                 {
                     Id = row.Id
                 }
查看更多
太酷不给撩
3楼-- · 2019-08-01 19:43

The issue is exactly as the error says...

An anonymous function or method group cannot be used as a constituent value of a dynamically bound operation.

It simply means that you can't use an anonymous function because one of the parameters is Type dynamic, so to fix your method you could simply cast the param to object

public static MyDbObject GetDbObjectFromTable(int id)
{
    string sql = @"SELECT Id FROM MyTable WHERE Id=@Id";

    dynamic param = new {Id = id}; // this Type dynamic is what causes the issue.

    // you could just fix with a cast to object
    return Query<MyDbObject>(sql, (object)param, mapper); 
}

Or presumably from looking at your code...simply.

    return Query<MyDbObject>(sql, id, mapper); 

The reason it doesn't complain when you use the Func delegate is because you never invoke the DLR by using the type dynamic so there is no dynamically bound operation.

查看更多
登录 后发表回答