1

我在这里有一点问题:但这个问题适用于任何方法重载。

我有一个方法声明,例如:(女巫不完全符合要求)

Public Shared Sub SetGridFormat(ByRef grid As DataGrid, ByVal width As Integer, ByVal height As Integer, ByVal paging As Boolean)

所以我想为我需要这个的情况写一个重载:

   Public Shared Sub SetGridFormat(ByRef grid As DataGrid, ByVal width As Unit, ByVal height As Unit, ByVal paging As Boolean)

这两个声明是相同的,但高度和宽度的类型。我收到“重载解析失败,因为没有可访问的 'SetGridFormat' 最适合这些参数”错误。

问题是:vb.net 是否允许“默认”定义方法,以防构建器无法决定使用哪一个以及语法是什么?

帮助的坦克。

编辑:这两个电话看起来像:

SetGridFormat(dg, New Unit(100, UnitType.Percentage), New Unit(100, UnitType.Percentage), True)
SetGridFormat(dg, 100, 100,True)

从回复中,我只需要指定一些内容:大多数答案在大多数情况下都可以使用,但排除我必须处理的有问题的情况,其中 2 个值可以设置为空(不需要特定大小)。

SetGridFormat(dg, Nothing, Nothing, True)

在这种情况下,从编译器的角度来看,两个方法声明是相同的:

这可能是问题的根本原因。如果这些情况不存在,我会非常失望。:(

我的问题是有没有办法强制编译器在这种情况下使用特定的方法调用?

4

3 回答 3

1

当然没有办法指定默认值。但是,您可以使用以下语法来执行缩小转换(如果我正确阅读了问题):

Public Shared Sub SetGridFormat(ByRef grid As DataGrid, ByVal iWidth As Integer, ByVal iHeight As Integer, ByVal paging As Boolean)
Public Shared Sub SetGridFormat(ByRef grid As DataGrid, ByVal uWidth As Unit, ByVal uHeight As Unit, ByVal paging As Boolean)

SetGridFormat(dg, iWidth:=50, iHeight:=50, true)
SetGridFormat(dg, uWidth:=50, uHeight:=50, true)

希望有帮助。

于 2012-08-09T14:04:09.580 回答
1

我认为没有默认说明符,但您不需要指定默认值,因为编译器将根据参数类型决定调用哪一个:

考虑以下:

Dim dg as DataGrid = Nothing
Dim widthInt as Integer = 0, HeightInt as Integer = 0
Dim pg as Boolean = False
Dim widthUnit as Unit = "Defaultvalue", heightUnit as Unit = "Defaultvalue"

SetGridFormat(dg, widthInt, heightInt, pg) ' Calls your first method
SetGridFormat(dg, widthUnit, heightUnit, pg) ' Calls your second method

如果您真的需要,您可以通过将类型转换为所需的类型来强制编译器使用特定方法(如果无法将对象转换为所需的类型,这显然会失败):

SetGridFormat(dg, CType(AnyObject,Integer), CType(AnyObject,Integer), pg) ' Calls your first method
SetGridFormat(dg, CType(AnyObject,Unit), CType(AnyObject,Unit), pg) ' Calls your first method

因此,在您想要调用特定方法的情况下,Nothing可以这样做:

SetGridFormat(dg, CType(Nothing,Integer), CType(Nothing,Integer), pg) ' Calls your first method
SetGridFormat(dg, CType(Nothing,Unit), CType(Nothing,Unit), pg) ' Calls your first method

但这首先对我来说似乎是糟糕的设计,因为使用Nothingas 参数调用一个或另一个应该具有相同的效果,所以在这种情况下调用哪个并不重要,所以我想你应该真正定义一个新的重载:

Public Shared Sub SetGridFormat(ByRef grid As DataGrid, ByVal paging As Boolean)
于 2012-08-09T13:16:48.277 回答
0

不,使用的方法必须由您定义,并且它将是所使用参数的最具体(按类型接近)。
如果你有 并且
yourMethod1(var1 as DataType1);
yourMethod1(var1 as DataType2);


DataType1 [extends DataType0];
DataType2 [extends DataType0];

那么您将不得不在对 yourMethod1(...) 的调用中使用 DataType1 或 DataType2(或扩展它们的某些类型)参数,否则调用将失败。

另一方面,如果
DataType1 [extends DataType0];
DataType2 extends DataType1;

那么您使用扩展 DataType2 类型的任何参数调用 toyourMethod1(...)将执行yourMethod1(var1 as DataType2)唯一的执行方式yourMethod1(var1 as DataType1)是使用 DataType1 类型的参数调用 yourMethod1(...) (或直接扩展 DataType1 - 不通过 DataType2)。

于 2012-08-09T13:25:45.490 回答