2016-01-06 51 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