C# 到 VB.Net : Why does this fail to compile when converted to VB?

标签 c# vb.net visual-studio-2008 generics .net-3.5

我有这个 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/

相关文章:

.net - 在 VB.NET 中实现 "optional delegate"的最佳方法是什么?

c# - C# : need to convert Y2K string to date format and use it to populate variable 中的 SSIS 2008 脚本

c# - 将动画的目标设置为运行时创建的自定义用户控件

c# - "The ' ObjectContent `1' 类型无法序列化内容类型“application/json”的响应正文

visual-studio - 当我按 END 时,如何让 Visual Studio 2008 忽略尾随空格?

c++ - 声明数组时 VS2008 错误预期常量表达式,但 GCC 中此代码没有错误

c# - 如何在 XNA 3.1 中导出模型的 3D "screenshot"?

c# - 在 Parallel.ForEach 中嵌套 await

mysql - VS 2017 MYsql 错误你已经有连接

mysql - 按数据库中的 Emp_ID 和信用日期插入最短日志时间和最长日志时间