Rei*_*ica 7 c# vb.net generics .net-3.5 visual-studio-2008
我有这个C#扩展方法,它将扩展Value类型为IList的任何字典.当我在VB.Net中编写等效代码时,我得到以下编译错误:
"扩展方法'添加'有一些永远无法满足的类型约束".
我觉得这实在令人费解的相同类型的限制可以在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);
}
Run Code Online (Sandbox Code Playgroud)
这是不能编译的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
Run Code Online (Sandbox Code Playgroud)
只有<System.Runtime.CompilerServices.Extension()>存在时才会出现问题.VB编译器强制要求约束必须仅使用第一个参数进行验证.由于扩展方法(Dictionary(Of KeyType, ListType))的第一个参数依赖于第三个参数(ValueType)通过IList(Of TValue)约束,因此无法在VB中编译.
| 归档时间: |
|
| 查看次数: |
695 次 |
| 最近记录: |