C# 无法隐式转换类型IEnumerable<;列表<;公制>&燃气轮机';至';IEnumerable<;公制>';。存在显式转换(是否缺少强制转换?)
我对c#advanced programming还不熟悉,所以很多东西对我来说都是很新的 我正在尝试扩展我的自定义字典对象,它有一个自定义类和一个键值对自定义类列表 在这个静态类中,我为字典的部分键扩展了一个部分匹配功能,它应该返回一个C# 无法隐式转换类型IEnumerable<;列表<;公制>&燃气轮机';至';IEnumerable<;公制>';。存在显式转换(是否缺少强制转换?),c#,linq,list,dictionary,extension-methods,C#,Linq,List,Dictionary,Extension Methods,我对c#advanced programming还不熟悉,所以很多东西对我来说都是很新的 我正在尝试扩展我的自定义字典对象,它有一个自定义类和一个键值对自定义类列表 在这个静态类中,我为字典的部分键扩展了一个部分匹配功能,它应该返回一个列表,而不是一个T public static class GADictionaryExtention { internal static List<T> PartialMatch<T>(this Dictionary<Key
列表,而不是一个T
public static class GADictionaryExtention
{
internal static List<T> PartialMatch<T>(this Dictionary<KeyDimensions, T> dictionary,
KeyDimensions partialKey)
{
IEnumerable<KeyDimensions> fullMatchingKeys = null;
fullMatchingKeys = dictionary.Keys.Where(currentKey => currentKey.Contains(partialKey));
List<T> returnedValues = new List<T>();
foreach (KeyDimensions currentKey in fullMatchingKeys)
{
returnedValues.Add(dictionary[currentKey]);
}
return returnedValues;
}
}
公共静态类GADictionaryExtention
{
内部静态列表PartialMatch(此字典,
钥匙(钥匙)
{
IEnumerable fullMatchingKeys=null;
fullMatchingKeys=dictionary.Keys.Where(currentKey=>currentKey.Contains(partialKey));
List returnedValues=新列表();
foreach(键尺寸currentKey in fullMatchingKeys)
{
returnedValues.Add(字典[currentKey]);
}
返回返回的值;
}
}
在我的调用代码中,我试图通过以下代码访问所有列表
结果
List<List<Metric>> m1 = DataDictionary.PartialMatch(kd);
List m1=DataDictionary.PartialMatch(kd);
但是我得到了以下错误
Cannot implicitly convert type
'System.Collections.Generic.IEnumerable<System.Collections.Generic.List<Metric>>'
to 'System.Collections.Generic.IEnumerable<Metric>'.
An explicit conversion exists (are you missing a cast?)
无法隐式转换类型
'System.Collections.Generic.IEnumerable'
至“System.Collections.Generic.IEnumerable”。
存在显式转换(是否缺少强制转换?)
您的调用调用应该如下所示:
List<Metric> m1 = DataDictionary.PartialMatch(kd);
List m1=DataDictionary.PartialMatch(kd);
因为您正在从扩展方法返回List
更新:
根据您的评论,T=List
,我认为,您应该按如下方式计算结果:
List<List<Metric>> m1 = (List<List<Metric>>)DataDictionary.PartialMatch(kd);
List m1=(List)数据字典.PartialMatch(kd);
数据字典类型的声明是什么?似乎您在某个地方错误地使用了列表而不是列表@spyronum您的代码看起来很好。我确信这个错误来自其他地方。尝试重新编译整件事。“显式转换存在”:我总是发现这个错误消息非常误导,因为它完全是错误的…@Spyronum,您发布的代码没有抛出这个异常。请仔细检查,如果你的代码和类型声明真的和这里发布的一样。很抱歉这里的混乱。T是代码T=List中类度量的自定义类型,因此我从扩展类中得到的是List或应该得到的,但我现在得到了错误。用于DataDictionary的类型声明是什么样的?请发布。@Sarwar026:强制转换将是多余的,请查看扩展方法的返回类型。@elgonzo请参阅我对您的评论的回复。我已经把申报单贴在那里了+sarwar026我试着按照你的建议去做,但仍然得到了错误。此外,我尝试在没有任何赋值的情况下放置方法调用,并且该行被标记为相同的错误标记,因此我怀疑错误是由扩展方法内部引起的。不在返回值或赋值处。还有其他建议吗?