【发布时间】:2021-12-04 17:16:08
【问题描述】:
@Hoshani 在答案中回答。
我为集合设计了一个字符串键Dictionary 结构,可以是List 或HashSet。两者都是string 集合,甚至字典键也是string。
我试图创建一个通用方法来添加到字典中的某个键,某个项目到集合中。但它甚至无法编译。
问题似乎不在于集合的泛型定义,而在于字典和集合的声明。 我无法继续,也无法检测到我做错了什么。 我需要帮助。这是代码:
using System;
using System.Collections.Generic;
// NO COMPILE ERROR CS1503
void AddToCollection<T,U>(U item, U key, Dictionary<U, ICollection<U>> dict)
where T : ICollection<U>, new()
{
if (key is not null) dict[item] = new T(){item};
else dict[key].Add(item);
}
var diccHS = new Dictionary<string, HashSet<string>>();
var diccLIST = new Dictionary<string, List<string>>();
// This two sentences DOES NOT COMPILE
AddToCollection<HashSet<string>, string>("item1", "item", diccHS);
AddToCollection<List<string>, string>("item1", "item", diccLIST);
// COMPILE OK - HERE THE CAST COMPILE
void test<T,U>( ICollection<U> col) where T : ICollection<U>, new() { var hs2 = new T(); }
var hset1 = new HashSet<string>{"hh"};
var list1 = new List<string>{"hh"};
test<HashSet<string>, string>(hset1);
test<List<string>, string>(list1);
谢谢
【问题讨论】:
-
与其编辑问题以说明它已被回答,请将答案标记为已接受(复选标记图标)。这将自动更新问题的标题以说明它已被回答,并且回答者将获得一些声誉分数以提供有用的答案。
标签: .net list dictionary hashset icollection