【问题标题】:How can I assign a placeholder datatype to custom classes dictionary in C#?如何将占位符数据类型分配给 C# 中的自定义类字典?
【发布时间】:2017-03-30 21:51:13
【问题描述】:

所以我注意到我一遍又一遍地使用很多相同的代码......所以我想在可能的情况下创建一个通用类,所以我没有在多个中重新定义相同的函数地方...

作为示例,我想尝试使用SortedDictionary 执行此操作。为此,我需要能够在创建自定义 SortedDictionary 时分配字典的数据类型。

这可能吗?像这样的:

using System.Collections.Generic;

namespace Controller.Framework
{
   class CSortedDictionary
   {
      private SortedDictionary<CustomDataType, CustomDataType> m_dictionary;
   }
}

// Create custom dictionary...
CSortedDictionary<int, List<string>> custom_dictionary
    = new CSortedDictionary<int, List<string>>();

【问题讨论】:

    标签: c# dictionary generics


    【解决方案1】:

    只需使用特定的泛型参数从 SortedDictionary 继承您的类。

    public class CSortedDictionary : SortedDictionary<int, List<string>>
    {
    }
    

    并使用CSortedDictionary - 它将具有List&lt;string&gt; 类型的整数键和值:

    CSortedDictionary custom_dictionary = new CSortedDictionary();
    custom_dictionary.Add(42, new List<string>());
    custom_dictionary[42].Add("Foo");
    

    【讨论】:

    • 是的,但是如何将 CustomDataType 分配给特定的数据类型?说 int 作为键, List 作为值?
    • @Ricky CSortedDictionary 将始终以 int 作为键,List&lt;string&gt; 作为值。不需要每次都指定这个泛型参数。
    【解决方案2】:

    我不清楚你在问什么,但我认为你只想创建自己的泛型来包装泛型 SortedDictionary

    using System.Collections.Generic;
    
    namespace Controller.Framework
    {
       class CSortedDictionary<CustomDataType1, CustomDataType2>
       {
          private SortedDictionary<CustomDataType1, CustomDataType2> m_dictionary;
    
          // other methods which work on m_dictionary;
       }
    }
    
    // Create custom dictionary...
    var custom_dictionary = new CSortedDictionary<int, List<string>>();
    

    或者像谢尔盖所说的那样继承

    using System.Collections.Generic;
    
    namespace Controller.Framework
    {
       class CSortedDictionary<CustomDataType1, CustomDataType2>: SortedDictionary<CustomDataType1, CustomDataType2> 
       {
          // other methods which work on m_dictionary;
       }
    }
    
    // Create custom dictionary...
    var custom_dictionary = new CSortedDictionary<int, List<string>>();
    

    也许您想考虑为SortedDictionary 提供一种扩展方法,尽管这不受欢迎。

    using System.Collections.Generic;
    
    namespace Controller.Framework
    {
       public static class CSortedDictionaryExtensions
       {
          public static DoSomething<CustomDataType1, CustomDataType2>(this SortedDictionary<CustomDataType1, CustomDataType2> dictionary){
            dictionary.SomeMethod();
          }
    
          // other methods which work on m_dictionary;
       }
    }
    
    // Create custom dictionary...
    var dictionary = new SortedDictionary<int, List<string>>();
    dictionary.DoSomething();
    

    [编写但未编译]

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 2019-07-12
      • 1970-01-01
      • 2016-11-03
      • 2017-03-18
      • 2022-01-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多