c# - 无法为接受 Expression<Func> 的方法推断实际类型

标签 c# type-inference expression

我正在编写一个小型库来解析存储过程的结果集(基本上,是一种非常特殊的 ORM)。

我有课

class ParserSetting<T> // T - type corresponding to particular resultset
{
    ...
    public ParserSettings<TChild> IncludeList<TChild, TKey>(
        Expression<Func<T, TChild[]>> listProp,
        Func<T, TKey> foreignKey,
        Func<TChild, TKey> primaryKey,
        int resultSetIdx)
    { ... }
}

这里的方法IncludeList指定结果集没有。 resultSetIdx 应该被解析为好像它由 TChild 对象组成,并分配给 listProp 表达式(作为数组)定义的属性。

我是这样使用它的:

class Parent
{
   public int ParentId {get;set;}
   ...
   public Child[] Children{get;set;}
}

class Child
{
   public int ParentId {get;set;}
   ...
}
ParserSettings<Parent> parentSettings = ...;
parentSettings.IncludeList(p => p.Children, p=> p.ParentId, c => c.ParentId, 1);

这个方法很有魅力。到目前为止,还不错。

除了数组之外,我还想支持不同类型的集合。所以,我正在尝试添加以下方法:

    public ParserSettings<TChild> IncludeList<TChild, TListChild, TKey>(
        Expression<Func<T, TListChild>> listProp,
        Func<T, TKey> foreignKey,
        Func<TChild, TKey> primaryKey,
        int resultSetIdx)
    where TListChild: ICollection<TChild>, new()
    { ... }

但是,当我尝试按如下方式使用它时:

class Parent
{
   public int ParentId {get;set;}
   ...
   public List<Child> Children{get;set;}
}

class Child
{
   public int ParentId {get;set;}
   ...
}
ParserSettings<Parent> parentSettings = ...;
parentSettings.IncludeList(p => p.Children, p=> p.ParentId, c => c.ParentId, 1);

C# 编译器发出错误消息“无法推断方法 ParserSettings.IncludeList(...) 的类型参数”。

如果我明确指定类型,它会起作用:

parentSettings.IncludeList<Child, List<Child>, int>(
    p => p.Children, p=> p.ParentId, c => c.ParentId, 1);

但这在某种程度上违背了使调用过于复杂的目的。

有没有办法实现这种场景的类型推断?

最佳答案

我还注意到 C# 编译器推断类型的能力在“拐角处”不起作用。

在您的情况下,您不需要任何其他方法,只需重写 Child[]作为ICollection<TChild>并且签名将匹配数组、列表等:

    public ParserSettings<TChild> IncludeList<TChild, TKey>(
        Expression<Func<T, ICollection<TChild>>> listProp,
        Func<T, TKey> foreignKey,
        Func<TChild, TKey> primaryKey,
        int resultSetIdx) {
            ...
        }

关于c# - 无法为接受 Expression<Func> 的方法推断实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15425939/

相关文章:

c# - 像 MVC4 Razor 模板

c# - 写入 FIFO 文件、Linux 和 Mono(C#)

c# - 在 Entity Framework 中使用存储过程(代码优先)

scala - 在Scala中,如何使用 `Nothing`作为Fake方法的返回值?

scala - 为什么 Scala 类型与预期的 Int 不匹配?

C# 在 lambda 中转换对象

javascript - 是否可以从字符串模板文字中推断泛型类型

c++ - 是否有一个 C/C++ 库可以让你找出一组表达式是否互斥?

r - 动态创建函数和表达式

C++ 表达式必须是可修改的左值