C# - 传递匿名函数作为参数 [英] C# - Passing an anonymous function as a parameter

查看:891
本文介绍了C# - 传递匿名函数作为参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用FluentData作为我的数据库的一个orm,我正在尝试创建一个通用的查询方法:

 内部静态T QueryObject T(String sql,object [] param,Func< dynamic,T> mapper)
{
返回MyDb.Sql(sql,param).QueryNoAutoMap< T>(mapper) .FirstOrDefault();
}

除了我班的功能:

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


public static MyDbObject mapper(dynamic row)
{
返回新的MyDbObject {
Id = row.Id
};
}

public static MyDbObject GetDbObjectFromTable(int id)
{
string sql = @SELECT Id FROM MyTable WHERE Id = @ Id;
dynamic param = new {Id = id};
返回查询< MyDbObject>(sql,param,mapper);
}

at 查询< MyDbObject>(sql,param,映射器)编译器说:



匿名函数或方法组将被用作动态的组成值任何人都知道这是什么意思?



编辑:



当我将方法转换为代理时,编译器不会抱怨:

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

它仍然提出一个问题,为什么一种方法是有效的,而不是另一种方式。

解决方案

编译器在我转换时不会抱怨将方法转换为代理:

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


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.

解决方案

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
                 }

这篇关于C# - 传递匿名函数作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆