引用 Label1.Text 作为对象 [英] Reference Label1.Text as Object
问题描述
如果我通过函数传递 Label1.Text,它会将其视为对象而不是字符串.哪个好.
If I pass Label1.Text through a function it treats it as an object and not a string. Which is good.
但是当我做这样的事情时:
But when I do something like:
Dim temp As Object = Label1.Text
然后将它传递给一个函数,它将其视为字符串,这是可以预料的.我怎样才能做到这样我就可以将 Label1.Text 设置为一个对象,就像我只是通过一个函数传递它一样.
And then pass it through a function it treats it as a string, which is to be expected. How can I make it so I can set Label1.Text to an object the same way it would if I just passed it through a function.
这是我特别想做的
Public Sub test()
setIt(Label1.Text, "Test") 'this works
Dim temp As Object = Label1.Text
setIt(temp, "Test") 'this doesnt work
End Sub
Public Sub setIt(ByRef e, ByVal v)
e = v
End Sub
推荐答案
字符串就是字符串,无论您是否将其向下转换为对象.您可以使用 typeof temp is String
(typeof-关键字).
A string is a string, regardless of you downcasting it to an object or not. You can check this with typeof temp is String
(typeof-keyword).
我不明白您的实际问题在哪里.
I don't understand where your actual problem is.
您不能使用给定对象设置标签的 Text 属性,因为 Label.Text 必须是字符串类型.但是您可以使用 Object 的 ToString 来获取字符串表示你的对象,或者如果你知道(用 typeof 检查)你的对象是 String 类型,你可以简单地将它转换回来:
You cannot set a Label's Text property with a given object because Label.Text must be of Type String. But you could use Object's ToString to get a String represantation of your Object or if you know(check with typeof) that your Object is of type String you can simply cast it back:
Label1.Text = DirectCast(temp , String)
根据您的更新,我强烈建议设置
According to your updates, i strongly recommend to set Option Strict! Why don't you simply assign the value to the Text property?
Label1.Text = "Test"
You're ByRef 方法非常容易出错且可读性不高.如果你真的需要这样的东西,你只想设置不同控件的Text属性,试试这个:
You're ByRef approach is very error-prone and not very readable. If you really need such thing and you only want to set the Text property of different controls, try this:
Public Sub setControlText(ByVal ctrl As Control, ByVal text String)
ctrl.Text = text
End Sub
或者如果您的文本"必须是对象类型:
or if your "text" must be of type Object:
Public Sub setControlText(ByVal ctrl As Control, ByVal value As Object)
If Not value Is Nothing Then ctrl.Text = value.ToString
End Sub
或者你可以使用反射来设置每个属性,但这不应该是标准的
or you can use reflection to set every property, but that should not be standard
Public Sub setProperty(ByVal obj As Object, ByVal propName As String, ByVal newValue As Object)
Dim prop As Reflection.PropertyInfo = obj.GetType().GetProperty(propName)
If Not prop Is Nothing AndAlso prop.CanWrite Then
prop.SetValue(obj, newValue, Nothing)
End If
End Sub
您可以通过以下方式调用此函数(请考虑属性名称区分大小写):
You can call this function in the following way(consider that the property-name is case sensitive):
setProperty(Label1, "Text", "Hello World!")
这篇关于引用 Label1.Text 作为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!