2010-09-28 68 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