2013-10-17 41 views
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 

再次選擇嚴格拋出由於後期綁定了一些錯誤,但他們應該有一個投來清理一次,我可以成功地正確聲明_manageComplexProperties變量,但我可以」 t似乎得到了一個解決方案,因爲在運行時間之前未知類型參數。任何幫助,將不勝感激。

回答

1

聲明你的變量爲Object

Private _manageComplexProperties as Object 

,然後你將有反映,如堅持撥打電話ShowDialog方法:

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

如果我那樣做了,我仍然不能在'Show()'方法中將'_manageComplexProperties'變量轉換爲任何東西,所以我可以使用'.ShowDialog()'或'.GetResult()'方法。我開始認爲在這種情況下你不能使用'Option Strict On'! – XN16

+0

你不能使用'DirectCast(_manageComplexProperties,YourType)'?好。你不能。一秒... – Szymon

+1

恐怕你需要反思,直到最後。查看我的編輯例子。 – Szymon

0

你必須在你的vb文件的頂部使用option infer on。它啓用當地type inference

使用此選項可讓您在沒有「As」的情況下使用Dim,它就像C#中的 var一樣。

智能感知當選項推斷和選項嚴格關斷

enter image description here

智能感知選項時推斷是(你可以看到它有類型推斷)

enter image description here

如果你這樣做不想使用選項推斷,您將不得不聲明與Activator.CreateInstance

返回的類型匹配的變量
+0

我不認爲這對我有用,無論是我還是我誤解了完全有可能的東西!實際上,我需要像這樣聲明變量:'Private _manageComplexProperties = ManageComplexProperties(Of)',但是它需要聲明中的一個類型,我不知道這一點。 – XN16

相關問題