在通用函数中使用集合

时间:2019-04-16 08:33:31

标签: c# generics collections

我试图对2种Collections使用通用函数,在其中我将方法称为Add。

所以在我的代码下面:

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void AddElement<T>(ref T container, string key, string value)
        {
            container.Add(key, value);
        }

        static void Main(string[] args)
        {
            SortedList s1 = new SortedList();
            Hashtable  h1 = new Hashtable();

            AddElement<SortedList>(ref s1, "001", "Zara Ali");
            AddElement<Hashtable>(ref h1, "001", "Zara Ali");
        }
    }
}

并显示以下错误:

  

错误CS1061:“ T”不包含“添加”的定义,并且没有   扩展方法'Add'接受类型'T'的第一个参数

那么这可以执行,如果可能的话如何解决?

谢谢。

3 个答案:

答案 0 :(得分:3)

这里的问题是T可以是任何东西(例如int),并且不能保证具有Add方法。

您需要将T约束为具有Add方法的东西。

static void AddElement<T>(ref T container, string key, string value)
    where T : IDictionary 
{
    container.Add(key, value);
}

答案 1 :(得分:2)

为什么不这样简单?

using System;
using System.Collections;

namespace CollectionsApplication
{
    class Program
    {
        static void AddElement(IDictionary container, string key, string value)
        {
            container.Add(key, value);
        }

        static void Main(string[] args)
        {
            SortedList s1 = new SortedList();
            Hashtable  h1 = new Hashtable();

            AddElement(s1, "001", "Zara Ali");
            AddElement(h1, "001", "Zara Ali");
        }
    }
}

答案 2 :(得分:2)

或创建扩展方法:

public static class MyExtensions
{
    public static void AddElement(this IDictionary container, string key, string value)
    {
        container.Add(key, value);
    }
}

和用法:

SortedList s1 = new SortedList();
Hashtable h1 = new Hashtable();

s1.AddElement("001", "Zara Ali");
h1.AddElement("001", "Zara Ali");