2016-01-06 112 views
0

我有一個類似於下面的示例設置我想要定義變量(var1)基於一些信息,當它被實例化時傳遞到類中。我怎麼做?如何有條件地定義變量?

Public Class myClass 

    Private var1 as someClass 

    Public Sub New(which_type as string) 

    if which_type = "a" then 
     ' I need var to be a certain type of class 
     var1 = new SomeClass() 
    elseif which_type = "b" then 
     ' I need var1 to be a different type of class 
     var1 = new SomeOtherClass() 
    end if 


    End Sub 

End Class 
+0

var1只能是一個或另一個......除非從另一個繼承 – Plutonix

回答

1

你不......在VB變量中必須有一個特定的數據類型。 Data Types in Visual Basic說:

編程元素的數據類型是指它可以容納什麼樣的數據以及它如何存儲數據。數據類型適用於所有可存儲在計算機內存中的值或參與表達式的評估。

每個變量都有一個數據類型。

爲了把不同類的對象到一個變量:

  • 它們必須具有一個共同的基類或接口,和
  • 變量,必須使用被宣稱通用類/接口。

共同的基礎

Public Class SomeClass 
     Inherits BaseClassOrInterface 
    End Class 

    Public Class SomeOtherClass 
     Inherits BaseClassOrInterface 
    End Class 

因此,在你的代碼:

Private var1 as BaseClassOrInterface 

現在VAR1可以容納任何(SomeClass的,SomeOtherClass,BaseClassOrInterface)的。

Public Sub New(which_type as string) 

     if which_type = "a" then 
      var1 = new SomeClass() 
     elseif which_type = "b" then 
      var1 = new SomeOtherClass() 
     end if 

    End Sub 

備選地可以聲明VAR1如System.Object,這是最終的基類(不推薦雖然)。

Private var1 as Object 
+0

謝謝。現在我明白了。 – user2721815

+0

爲什麼你不推薦使用'object'? – user2721815

+0

因爲沒有太多可以做的事情,除了把它轉換成另一種數據類型 - 那麼你會得到運行時崩潰。使用通用的基類,任何錯誤都會在編譯時被捕獲。 – buffjape

0

這隻能做,如果它有一個基本類型如下面(C#示例)

public interface Ibase { } 

public class someclass : Ibase {} 

public class someotherclass : Ibase {} 

那麼你可以說

Private var1 as Ibase 

    Public Sub New(which_type as string) 

if which_type = "a" then 
    ' I need var to be a certain type of class 
    var1 = new SomeClass() 
elseif which_type = "b" then 
    ' I need var1 to be a different type of class 
    var1 = new SomeOtherClass() 
end if 
0

您可以使用Activator.CreateInstance(Type.GetType("ClassA"))以實例的ClassA類。見this