1

我的以下代码已经运行了好几个月,但是我忘记了创建这个类,Option Strict On所以现在我要回去正确地清理我的代码,但是我无法找到解决以下问题的方法。

我有一个像这样声明的局部变量:

Private _manageComplexProperties

现在使用选项严格,由于没有我理解的子句,这是不允许的As,但是之所以这样,是因为将分配给它的类的实例需要一个类型参数,直到运行才知道时间。这是通过以下代码解决的:

Private _type As Type
*SNIP OTHER IRRELEVANT VARIABLES*

Public Sub Show()

    Dim requiredType As Type = _
        GetType(ManageComplexProperties(Of )).MakeGenericType(_type)

    _manageComplexProperties = Activator.CreateInstance(requiredType, _
         New Object() {_value, _valueIsList, _parentObject, _unitOfWork})

    _result = _manageComplexProperties.ShowDialog(_parentForm)
    If _result = DialogResult.OK Then
        _resultValue = _manageComplexProperties.GetResult()
    End If

End Sub

由于后期绑定,选项 strict 再次引发了一些错误,但是一旦我可以成功_manageComplexProperties正确声明变量,就应该使用强制类型转换来清除它们,但由于类型参数未知,我似乎无法获得有效的解决方案,直到运行。任何帮助,将不胜感激。

4

2 回答 2

1

将您的变量声明为Object

Private _manageComplexProperties as Object

然后你将不得不坚持反射,例如调用ShowDialog方法:

Dim method As System.Reflection.MethodInfo = _type.GetMethod("ShowDialog")
_result = method.Invoke(_manageComplexProperties, New Object() {_parentForm})
于 2013-10-17T11:28:26.633 回答
0

您必须option infer on在 vb 文件的顶部使用。它启用本地type inference.

使用此选项允许您在Dim没有“As”分句的情况下使用,就像 var在 C# 中一样。

当 Option Infer 和 Option Strict 关闭时的 IntelliSense

在此处输入图像描述

选项推断打开时的智能感知(如您所见,它具有类型推断)

在此处输入图像描述

如果您不想使用 option infer on,则必须声明与返回的类型匹配的变量 Activator.CreateInstance

于 2013-10-17T11:17:35.150 回答