2013-03-15 67 views
4

我正在編寫一個小型庫來解析存儲過程的結果集(基本上,非常特殊的一種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); 

但這是有點失敗的目的撥打電話太複雜。

有沒有一種方法來實現這種情況下的類型推斷?

+0

@HamletHakobyan,我要創建分配與新物業映射期間的收集值。一些東西沿着: 'var childrenBuckets = childrenResultSet.ToLookup(primaryKey); (父parentResultSet){ var value = childrenBuckets [foreignKey(parent)]; setProperty(parent,new TList {value}); }' 如果我不能通過'new'創建值' – 2013-03-15 06:29:22

+0

'作爲@devio提及的'ICollection',將會變得更加困難。我對這個問題的'理論上的'方面很感興趣,在期望類型引用能夠解決這個問題時我沒有看錯。 – 2013-03-16 13:14:10

回答

0

我還注意到,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) { 
      ... 
     } 
+1

有趣。你有沒有參考類型推斷這樣的陷阱? – 2013-03-15 08:05:00

+0

我想在數據解析期間在場景後面創建集合。這意味着理想情況下我需要特定類型(和「new()」約束)或者爲每個屬性使用Activator.CreateInstance(我寧願避免)。 – 2013-03-15 17:03:05

+0

傳遞一個ICollection工廠,而不是暗示集合類型 – devio 2013-03-15 17:36:35

相關問題