【发布时间】: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))':不是最具体的。
-
基类程序集
示例:
public class Base { protected void SetValue<T>(T newValue, ref T oldValue) { } protected void SetValue<T>(T? newValue, ref T? oldValue) where T : struct { } } -
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); } } -
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 会是一样的。
-
这闻起来像编译器错误。你应该举报。
-
杰夫,感谢您恢复我原来的通用代码。