【问题标题】:C Sharp - Compiler error CS1503 - cannot convert from Dictionary, ICollection, List, HashSetC Sharp - 编译器错误 CS1503 - 无法从 Dictionary、ICollection、List、HashSet 转换
【发布时间】:2021-12-04 17:16:08
【问题描述】:

@Hoshani 在答案中回答。

我为集合设计了一个字符串键Dictionary 结构,可以是ListHashSet。两者都是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


【解决方案1】:

基本上你在说什么 Dictionary&lt;U, ICollection&lt;U&gt;&gt;是字典的值部分对于每个键值对可以是ICollection的任意类型。

但是,在代码 var diccHS = new Dictionary&lt;string, HashSet&lt;string&gt;&gt;() 中,您将该类型限制为仅限 HashSet

例如,下面的代码不会产生您遇到的问题

var keyValuePairs = new Dictionary<string, ICollection<string>>(){
    {"key", new HashSet<string>()},
    {"key2", new List<string>()}
};
AddToCollection<HashSet<string>, string>("item1", "item", keyValuePairs);

话虽如此,我认为在您的问题中,您希望所有值都具有相同的类型,因此您应该像这样修复字典的第二部分:

void AddToCollection<T, U>(U item, U key, Dictionary<U, T> dict)
     where T : ICollection<U>, new()
{
    if (key is not null) dict[item] = new T() { item };
    else dict[key].Add(item);
}

【讨论】:

  • 你是对的!现在它起作用了。错误的定义。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-09
  • 2016-11-09
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2018-09-25
相关资源
最近更新 更多