代码之家  ›  专栏  ›  技术社区  ›  Youssef

在vb.net中铸造

  •  14
  • Youssef  · 技术社区  · 17 年前

    我希望能够在类型仅在运行时已知的情况下动态地强制转换值。像这样:

    myvalue = CType(value, "String, Integer or Boolean")
    

    包含类型值的字符串作为参数传递,也从数据库中读取,该值作为字符串存储在数据库中。

    这有可能吗?

    5 回复  |  直到 11 年前
        1
  •  7
  •   Peter Mortensen Pieter Jan Bonestroo    11 年前

    当然,但是 myvalue 必须定义为 Object 你不一定想要。也许这是一个更好的案例,由仿制药服务。

    什么决定将使用哪种类型?

        2
  •  9
  •   tom.dietrich    17 年前
     Dim bMyValue As Boolean
     Dim iMyValue As Integer
     Dim sMyValue As String 
     Dim t As Type = myValue.GetType
    
    
     Select Case t.Name
         Case "String"
            sMyValue = ctype(myValue, string)
         Case "Boolean"
            bMyValue = ctype(myValue, boolean)
         Case "Integer"
            iMyValue = ctype(myValue, Integer)
     End Select
    

    虽然有点老土,但还是可以用的。

        3
  •  5
  •   J. Steen    13 年前

    这是最短的方法。我用多种类型测试过它。

    Sub DoCast(ByVal something As Object)
    
        Dim newSomething = Convert.ChangeType(something, something.GetType())
    
    End Sub
    
        4
  •  4
  •   Konrad Rudolph    17 年前

    那么,您如何确定需要哪种类型?如乔尔所说,这可能是仿制药的一个例子。问题是:因为您在编译时不知道类型,所以无论如何都不能处理返回的值,所以这里的强制转换并没有真正意义。

        5
  •  2
  •   Sam Corder    17 年前

    也许你可以用反射代替动态投射(看起来不起作用)。获取和调用特定的方法或属性非常容易。

    Dim t As Type = testObject.GetType()
    Dim prop As PropertyInfo = t.GetProperty("propertyName")
    Dim gmi As MethodInfo = prop.GetGetMethod()
    gmi.Invoke(testObject, Nothing)
    

    它不漂亮,但你可以在一行中做一些,而不是这么多。

    推荐文章