gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 13:02:25 66 4
gpt4 key购买 nike

我正在编写一个小型库来解析存储过程的结果集(基本上,是一种非常特殊的 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/

66 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com