c# - 通用扩展方法 : Type argument cannot be inferred from the usage

标签 c# database generics lambda

我正在尝试创建一个适用于类型化数据表的通用扩展方法:

public static class Extensions
{
    public static TableType DoSomething<TableType, RowType>(this TableType table, param Expression<Func<RowType, bool>>[] predicates)
        where TableType : TypedTableBase<RowType>
        where RowType : DataRow
    {
        // do something to each row of the table where the row matches the predicates
        return table;
    }

    [STAThread]
    public static void main()
    {
        MyTypedDataSet.MyTypedDataTable table = getDefaultTable();
    }

    public static MyTypedDataSet.MyTypedDataTable getDefaultTable()
    {
        // this line compiles fine and does what I want:
        return new MyTypedDataSet.MyTypedDataTable().DoSomething<MyTypedDataSet.MyTypedDataTable, MyTypedDataSet.MyTypedRow>(row => row.Field1 == "foo");

        // this line doesn't compile :
        return new MyTypedDataSet.MyTypedDataTable().DoSomething(row => row.Field1 == "foo");
        // Error : The type arguments .. cannot be inferred from the usage
    }
}

第一行工作正常,但它真的很丑......
第二行没有编译,因为编译器无法推断 RowType 的类型。
这是一种将被许多不同的程序员用作 DataLayer 的一部分的方法,因此我宁愿不需要他们指定 TypeParameter。
编译器难道不应该知道 RowType 与 TypedTableBase 使用的类型相同吗?

出于在此代码示例中可能并不明显的不同原因,我确实需要以其原始形式返回数据表。我需要 RowType 的原因是 'Expression <函数< T, bool > > ' 将由 InteliSence 键入和查看。

谢谢

最佳答案

方法类型推断不会根据约束 的参数进行推断。它根据参数对形式参数 进行推断,然后检查根据参数对形式参数所做的推断是否满足约束条件。

在你的情况下,没有足够的参数数据来推断类型参数是什么而不首先查看约束,我们不会这样做直到我们根据约束检查推论。抱歉,这就是指定类型推断算法的方式。

关于这个问题我被问过很多次,大家的共识似乎是,我坚持推论应该仅从参数推导出形式参数的立场在道德上是错误的。关于十几个人告诉我我在这方面的想法是错误的,请参阅我对这个密切相关问题的分析的评论:

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

我保持我的立场。

关于c# - 通用扩展方法 : Type argument cannot be inferred from the usage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36909644/

相关文章:

c# - 将 c# 代码文件转换为一个 html 文件?

c# - 从服务器下载文件,然后在服务器上删除

c# - 再次为特定异常启用 Break

mysql - 具有权限的 mysql 用户不可见数据库

mysql - 如何在自引用表中添加记录?

c# - 如何在 C# 中确保对象的类型等于此?

Scala:是否可以将类型参数限制为非抽象?

swift - 协议(protocol)只能用作通用约束

c# - Visual Studio 2012没有调试选项

java - 如何在 Android Studio 中将数据库中的列显示到 TextView 中?