如何在C#中将占位符数据类型分配给自定义类字典?

时间:2017-03-30 21:51:14

标签: c# dictionary generics

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

作为一个例子,我想尝试用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>>();

2 个答案:

答案 0 :(得分:0)

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

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

并使用CSortedDictionary - 它将具有List<string>类型的整数键和值:

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

答案 1 :(得分:0)

我不清楚你在问什么,但我认为你只想创建自己的通用包装通用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();

[书面但未编译]