Skip to main content
 首页 » 编程设计

c#之在泛型函数中使用集合

2024年01月22日31JeffreyZhao

我试图对 2 种集合使用通用函数,我在其中调用方法 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"); 
        } 
    } 
} 

错误下方:

error CS1061: 'T' does not contain a definition for 'Add' and no extension method 'Add' accepting a first argument of type 'T'

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

提前谢谢你。

请您参考如下方法:

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

您需要将 T 限制为具有 Add 方法的对象。

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