我有这个 C# 扩展方法,它可以扩展 Value 类型为 IList 的任何字典。当我在 VB.Net 中编写等效代码时,出现以下编译错误:
"Extension method 'Add' has some type constraints that can never be satisfied".
我发现这真的很令人费解,因为 相同 类型约束可以在 C# 中得到满足。
所以我的问题是:为什么这在 VB 中不起作用?有没有办法使这些相同类型的约束在 VB 中起作用?我在转换代码时犯了错误吗?我希望有人能对此有所了解,因为我已经为此挠头了一段时间。 :)
(如果您好奇扩展方法旨在简化在单个键(例如一个客户下的多个订单)下将多个值添加到字典中的过程。但这并不重要,我只关心我在 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
最佳答案
问题只发生在 <System.Runtime.CompilerServices.Extension()>
时存在。
VB 编译器施加了一个限制,即约束必须可以单独使用第一个参数进行验证。由于扩展方法的第一个参数 ( Dictionary(Of KeyType, ListType)
) 依赖于第三个参数 ( ValueType
) 通过 IList(Of TValue)
约束,这不能在 VB 中编译。
关于C# 到 VB.Net : Why does this fail to compile when converted to VB?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/341103/