我正在編寫一個小型庫來解析存儲過程的結果集(基本上,非常特殊的一種ORM)。無法爲接受方法推斷實際類型<Func>
我有類
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);
但這是有點失敗的目的撥打電話太複雜。
有沒有一種方法來實現這種情況下的類型推斷?
@HamletHakobyan,我要創建分配與新物業映射期間的收集值。一些東西沿着: 'var childrenBuckets = childrenResultSet.ToLookup(primaryKey); (父parentResultSet){ var value = childrenBuckets [foreignKey(parent)]; setProperty(parent,new TList {value}); }' 如果我不能通過'new'創建值' – 2013-03-15 06:29:22
'作爲@devio提及的'ICollection',將會變得更加困難。我對這個問題的'理論上的'方面很感興趣,在期望類型引用能夠解決這個問題時我沒有看錯。 – 2013-03-16 13:14:10