1

我正在尝试使用 3.5 框架将以下代码从 C# 转换为 Vb。

这是我遇到问题的 C# 代码。

MethodInfo mi = typeof(Page).GetMethod("LoadControl", new Type[2] { typeof(Type), typeof(object[]) });

我以为在VB中会是这样;

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type(2) {GetType(Type), GetType(Object())})

但我收到以下错误“数组初始化程序缺少 1 个元素”

我遇到问题并遇到相同错误的另一行是

control = (Control) mi.Invoke(this.Page, new object[2] { ucType, null });

我在vb中尝试过,但它不起作用。

control = DirectCast(mi.Invoke(Me.Page, New Object(2) {ucType, Nothing}), Control)

ucType 定义如下

Dim ucType As Type = Type.[GetType](typeName(1), True, True)

任何帮助将不胜感激。

4

6 回答 6

6

VB.Net 数组是从 0 开始的,但使用最高索引而不是项目数声明。因此,索引为 0..9 的 10 项数组被声明为 Item(9)。

话虽如此,解决问题的真正方法是让编译器计算出数组长度,如下所示:

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type() {GetType(Type), GetType(Object())})
于 2009-05-04T15:26:18.910 回答
5

在 VB.NET 中,数组声明采用数组的上限,而不是像 C# 那样的长度(如果你问我,有点傻)。因此,您需要将传递给数组声明的数量减少 1(因为数组是从零开始的)。

于 2009-05-04T15:28:02.570 回答
3

对于第一行,您需要将 new Type(2) 更改为 New Type(1)。

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type(1) {GetType(Type), GetType(Object())})

在 VB.Net 中,数组初始值设定项中指定的数字是最高可访问索引与长度的关系。您提到的第二行具有相同的问题和解决方案。

于 2009-05-04T15:25:58.643 回答
2

VB 使用上限作为数组的参数。

new byte[X]

new byte(X) 'wrong, 1 more element
new byte(X-1) 'correct, kinda confusing
new byte(0 to X-1) 'correct, less confusing

我建议使用 (0 to X-1) 样式,因为它更清晰。在 vb6 的日子里,当 array(X) 根据上下文可能意味着 0 到 X 或 1 到 X 时,这一点要重要得多。

于 2009-05-04T15:36:01.117 回答
1

会是这样——

Dim mi As MethodInfo = GetType(Page).GetMethod("LoadControl", New Type(1) {GetType(Type), GetType(Object())})

另一个将是——

control = DirectCast(mi.Invoke(Me.Page, New Object(1) {ucType, Nothing}), Control)
于 2009-05-04T15:25:51.623 回答
1

http://converter.telerik.com上有一个在线版本,可以将 C# 转换为 VB,反之亦然。

于 2009-05-04T16:20:49.853 回答