在 VB.NET 中进行转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/251482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Casting in VB.NET
提问by Youssef
I would like to be able to cast a value dynamically where the type is known only at runtime. Something like this:
我希望能够动态地转换一个值,其中类型仅在运行时已知。像这样的东西:
myvalue = CType(value, "String, Integer or Boolean")
The string that contains the type value is passed as an argument and is also read from a database, and the value is stored as string in the database.
包含类型值的字符串作为参数传递,也从数据库中读取,并将该值作为字符串存储在数据库中。
Is this possible?
这可能吗?
采纳答案by Joel Coehoorn
Sure, but myvalue
will have to be defined as of type Object
, and you don't necessarily want that. Perhaps this is a case better served by generics.
当然,但myvalue
必须定义为 type Object
,而您不一定想要那样。也许这是泛型更好地服务的情况。
What determines what type will be used?
什么决定了将使用什么类型?
回答by tom.dietrich
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
It's a bit hacky but it works.
这有点hacky,但它有效。
回答by Inisheer
This is the shortest way to do it. I've tested it with multiple types.
这是最短的方法。我已经用多种类型对其进行了测试。
Sub DoCast(ByVal something As Object)
Dim newSomething = Convert.ChangeType(something, something.GetType())
End Sub
回答by Konrad Rudolph
Well, how do you determine which type is required? As Joel said, this is probably a case for generics. The thing is: since you don't know the type at compile time, you can't treat the value returned anyway so casting doesn't really make sense here.
那么,您如何确定需要哪种类型?正如乔尔所说,这可能是泛型的一个例子。问题是:由于您在编译时不知道类型,因此无论如何您都无法处理返回的值,因此这里的强制转换实际上没有意义。
回答by Sam Corder
Maybe instead of dynamically casting something (which doesn't seem to work) you could use reflection instead. It is easy enough to get and invoke specific methods or properties.
也许不是动态投射某些东西(这似乎不起作用),您可以改用反射。获取和调用特定的方法或属性很容易。
Dim t As Type = testObject.GetType()
Dim prop As PropertyInfo = t.GetProperty("propertyName")
Dim gmi As MethodInfo = prop.GetGetMethod()
gmi.Invoke(testObject, Nothing)
It isn't pretty but you could do some of that in one line instead of so many.
它并不漂亮,但您可以在一行中完成其中的一些而不是这么多。