【发布时间】:2010-09-25 08:40:33
【问题描述】:
我有这个 C# 扩展方法,它可以扩展任何 Value 类型为 IList 的字典。当我在 VB.Net 中编写等效代码时,出现以下编译错误:
“扩展方法 'Add' 有一些永远无法满足的类型约束”。
我觉得这真的很令人费解,因为 same 类型约束可以在 C# 中得到满足。
所以我的问题是:为什么这在 VB 中不起作用?有没有办法让这些相同的类型约束在 VB 中起作用?我是不是在转换代码时出错了?我希望有人能对此有所了解,因为我一直在摸索这个问题。 :)
(如果您好奇,扩展方法旨在简化在 single 键下将多个值添加到字典中(例如一个客户下的多个订单)。但这不重要,我只关心我在 VB 中观察到的令人费解的行为)。
这是可用的 C# 版本:
/// <summary>
/// Adds the specified value to the multi value dictionary.
/// </summary>
/// <param name="key">The key of the element to add.</param>
/// <param name="value">The value of the element to add. The value can be null for reference types.</param>
public static void Add<KeyType, ListType, ValueType>(this Dictionary<KeyType, ListType> thisDictionary,
KeyType key, ValueType value)
where ListType : IList<ValueType>, new()
{
//if the dictionary doesn't contain the key, make a new list under the key
if (!thisDictionary.ContainsKey(key))
{
thisDictionary.Add(key, new ListType());
}
//add the value to the list at the key index
thisDictionary[key].Add(value);
}
这是无法编译的 VB 版本:
''' <summary>
''' Adds the specified value to the multi value dictionary.
''' </summary>
''' <param name="key">The key of the element to add.</param>
''' <param name="value">The value of the element to add. The value can be null for reference types.</param>
<System.Runtime.CompilerServices.Extension()> _
Public Sub Add(Of KeyType, ListType As {IList(Of ValueType), New}, ValueType) _
(ByVal thisDictionary As Dictionary(Of KeyType, ListType), ByVal key As KeyType, ByVal value As ValueType)
'if the dictionary doesn't contain the key, make a new list under the key
If Not thisDictionary.ContainsKey(key) Then
thisDictionary.Add(key, New ListType())
End If
'add the value to the list at the key index
thisDictionary(key).Add(value)
End Sub
【问题讨论】:
-
它给出的错误是什么?
-
"扩展方法 'Add' 有一些永远无法满足的类型约束"。
标签: c# vb.net visual-studio-2008 generics .net-3.5