C# - Passing an anonymous function as a parameter

五迷三道 提交于 2019-12-11 12:18:27

问题


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.


回答1:


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.




回答2:


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
                 }


来源:https://stackoverflow.com/questions/10899761/c-sharp-passing-an-anonymous-function-as-a-parameter

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