【问题标题】:Option Strict On issues where generic type isn't known until runtimeOption Strict 关于泛型类型直到运行时才知道的问题
【发布时间】:2013-10-17 11:15:11
【问题描述】:

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

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

Private _manageComplexProperties

现在使用选项 strict,这是不允许的,因为我理解没有 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 变量,就应该使用强制类型转换来清除它们,但我似乎无法获得有效的解决方案,因为直到运行时才知道类型参数。任何帮助将不胜感激。

【问题讨论】:

    标签: vb.net type-parameter option-strict


    【解决方案1】:

    将您的变量声明为Object

    Private _manageComplexProperties as Object
    

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

    Dim method As System.Reflection.MethodInfo = _type.GetMethod("ShowDialog")
    _result = method.Invoke(_manageComplexProperties, New Object() {_parentForm})
    

    【讨论】:

    • 如果我这样做,我仍然无法将Show() 方法中的_manageComplexProperties 变量转换为任何东西,因此我可以使用.ShowDialog().GetResult() 方法。我开始认为你不能在这种情况下使用Option Strict On
    • 你不能用DirectCast(_manageComplexProperties, YourType)吗?好的。你不能。一秒……
    • 恐怕你需要使用反射直到最后。以我的编辑为例。
    • 在属性而不是方法方面做一些额外的工作,获得正确的重载和强制转换,我的代码现在可以像以前一样工作了,非常感谢!
    【解决方案2】:

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

    使用此选项允许您使用不带“As”分句的Dim,就像 C# 中的var

    Option Infer 和 Option Strict 关闭时的 IntelliSense

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

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

    【讨论】:

    • 我不认为这对我有用,或者我误解了一些完全可能的事情!实际上,我需要像这样声明变量:Private _manageComplexProperties = ManageComplexProperties(Of ),但是它需要声明中的类型,我当时不知道。
    猜你喜欢
    • 1970-01-01
    • 2019-01-21
    • 2011-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-19
    相关资源
    最近更新 更多