2010-09-28 92 views
1

我發現自己需要「結合」幾個相同類型的實例。這種類型有幾個IList屬性。我想獲取每個實例並將這些IList屬性的值合併到實例中,因此我的代碼只需要其中一個實例。ICombinable .NET接口

我正在考慮創建一個ICombinable接口,但我想知道是否有一些東西已經在那裏適合這個了?

public interface ICombinable<T> 
    { 
     void CombineWith(T instance); 
    } 
+0

聽起來像代碼味道給我.....? – 2010-09-28 03:18:14

+0

請參閱更多信息。你將如何使用這個接口? – 2010-09-28 03:18:16

+0

// @米奇:代碼味道?那是什麼? – Jeff 2010-09-28 03:18:51

回答

0

我結束了使用和的SelectMany選擇此。 IConfiguration是MyConfigurationInfo類的接口。 GetMyConfigurationSources返回所有不同的IC配置(從文件,數據庫等)。

// accumulates an enumerable property on IConfiguration 
    public static IEnumerable<TValue> GetConfigurationValues<TValue>(Func<IConfiguration, IEnumerable<TValue>> selector) 
    { 
     // cast included for clarification only 
     return (GetMyConfigurationSources() as IEnumerable<IConfiguration>) 
      .Where(c => selector(c) != null) 
      .SelectMany(selector); 
    } 

    // accumulates a non enumerable property on IConfiguration 
    public static IEnumerable<TValue> GetConfigurationValues<TValue>(Func<IConfiguration, TValue> selector) 
    { 
     // cast included for clarification only 
     return (GetMyConfigurationSources() as IEnumerable<IConfiguration>) 
      .Where(c => selector(c) != null) 
      .Select(selector); 
    } 

    // Example usage: 
    static void Main() 
    { 
     string[] allEnumerableValues = GetConfigurationValues(c => c.SomeEnumerableConfigPropertyOfStrings); 
     string[] allNonEnumerableValues = GetConfigurationValues(c => c.SomeNonEnumerableConfigPropertyString); 
    } 
0

聽起來像是你需要Concat

var configs = dbConfig.configList.Concat(fileConfig.configList); 
+0

但我有幾個這些configLists fileConfig和dbConfig需要concatanating ...然後我希望它們都可以通過MyConfigurationInfo的單個實例進行訪問。 – Jeff 2010-09-28 03:40:19

+0

與現有解決方案進行比較,肯定沒有足夠的信息,但聽起來像您試圖簡化您的配置。我建議你退後一步並分析你的設計。爲什麼你有多個配置信息源?如果有合理的理由,那麼你應該能夠建立一個基於這個邏輯的提供者,這個邏輯可以連貫地暴露你的配置。但從你的描述來看,我很難對設計進行反思。 – arootbeer 2010-09-28 04:36:26

+0

我有兩個不同的配置來源相同的結構。一個是安裝特定的配置信息(存儲在xml配置文件中)。第二個是通過WCF從數據庫中提取的應用程序範圍配置設置。這有幫助嗎? – Jeff 2010-09-28 18:23:18

1

你試過看着System.Collections.Generic.HashSet<T>?如果多次添加相同的東西,則只存在1個項目。

+0

問題不在於如何區分價值觀,而在於如何聚合並以流暢的方式訪問它們。儘管+1,將獨特的HashSet併入Select/SelectMany解決方案中是一個好主意! – Jeff 2010-10-07 15:50:06