【问题标题】:Generic method overloading compilation error in VBVB中的泛型方法重载编译错误
【发布时间】:2009-08-05 00:37:26
【问题描述】:

我有一个问题,VB.NET 编译器无法编译一个类(在单独的 C# 程序集中),该类包含具有泛型参数的方法的两个重载。 C# 中的等效代码针对同一个程序集进行编译,没有错误。

这是两个方法签名:

protected void SetValue<T>(T newValue, ref T oldValue)
protected void SetValue<T>(T? newValue, ref T? oldValue) where T : struct

这是演示问题的三个程序集的代码。第一个是具有实现泛型方法的基类的 C# 程序集。第二个是从 Base 派生的 C# 类,并正确调用 SetValue 的两个重载。第三个是同样从 Base 派生的 VB 类,但编译失败并出现以下错误消息:

错误 1 ​​重载解析失败,因为没有可访问的“SetValue”对这些参数最具体: 'Protected Sub SetValue(Of T As Structure)(newValue As System.Nullable(Of Integer), ByRef oldValue As System.Nullable(Of Integer))':不是最具体的。 'Protected Sub SetValue(Of T)(newValue As System.Nullable(Of Integer), ByRef oldValue As System.Nullable(Of Integer))':不是最具体的。

  1. 基类程序集

    示例:

    public class Base
    {
        protected void SetValue<T>(T newValue, ref T oldValue)
        {
        }               
        protected void SetValue<T>(T? newValue, ref T? oldValue) where T : struct
        {
        }
    }
    
  2. C#派生类

    示例:

    public class DerivedCSharp : Base
    {
        private int _intValue;
        private int? _intNullableValue;    
        public void Test1(int value)
        {
            SetValue(value, ref _intValue);
        }        
        public void Test2(int? value)
        {
            SetValue(value, ref _intNullableValue);
        }
    }
    
  3. VB派生类

    示例:

    Public Class DerivedVB
        Inherits Base    
        Private _intValue As Integer
        Private _intNullableValue As Nullable(Of Integer)    
        Public Sub Test1(ByVal value As Integer)
            SetValue(value, _intValue)
        End Sub    
        Public Sub Test2(ByVal value As Nullable(Of Integer))
            SetValue(value, _intNullableValue)
        End Sub
    End Class
    

我是在 VB 代码中做错了什么,还是 C# 和 VB 在通用重载解决方案方面有所不同?如果我在 Base 非泛型中设置方法参数,那么一切都会正确编译,但是我必须为我希望支持的每种类型实现 SetValue。

【问题讨论】:

  • 您使用的是什么版本的 Visual Studio 和 .Net?
  • 我在 VS2005 和 VS2010 Beta 1 中尝试过,结果相同。我假设 VS2008 会是一样的。
  • 这闻起来像编译器错误。你应该举报。
  • 杰夫,感谢您恢复我原来的通用代码。

标签: c# vb.net generics


【解决方案1】:

我坚持我的意见,这很可能是一个错误。但是,我可以使用 Mono VB 编译器vbnc 重现它。此处的(有些损坏的)错误消息是“No non-narrowing (except object)”——我认为这是指缺少隐式转换,因此是相同的重载解决问题。

问题似乎是编译器的重载解析由于ByRef 参数而失败,因为这需要一些特殊的管理,这些管理在 C# 调用中明确,但在 VB 调用中没有。

【讨论】:

    【解决方案2】:

    看来您必须稍微帮助 VB 编译器来选择正确的重载来调用。以下为我编译

    Public Sub Test1(ByVal value As Integer)
        SetValue(Of Integer)(value, _intValue)
    End Sub
    
    Public Sub Test2(ByVal value As Nullable(Of Integer))
        SetValue(Of Integer)(value, _intNullableValue)
    End Sub
    

    【讨论】:

    • 这绕过了编译器错误,但在 Test2 中对 SetValue 的调用解决了错误的重载。很好的尝试!我以为正确编译后问​​题就解决了。
    • 对不起,我的错。我现在编辑了我的回复,以便 Test1 调用 SetValue(T, ref T) 和 Test2 调用 SetValue(T?, ref T?)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多