我正在调试我工作中的一个应用程序,遇到了一个有趣的问题。对于不熟悉VB.NET的人来说,变量名是大小写不敏感的。因此,
Dim foo As Integer
FOO = 5
System.Console.WriteLine(foO)
这段代码将编译并输出值为5。
无论如何,我正在处理的代码试图通过反射从属性中获取一个值,代码如下:
Dim value As Object = theObject.GetType().GetProperty("foo", BindingFlags.Public Or BindingFlags.Instance).GetValue(theObject, Nothing)
代码在这一行抛出了NullReferenceException异常。经过调试,我注意到是GetProperty方法返回了Nothing,因此GetValue失败了。查看theObject类,它有一个名为"Foo"的公共属性,而不是"foo"(注意大小写的区别)。显然,由于我在反射中搜索小写的foo,它根本找不到该属性。
认为这是一些奇怪的偶然事件,我创建了一个快速而简单的沙盒应用程序来测试这个发现:
Option Strict On
Option Explicit On
Imports System.Reflection
Module Module1
Sub Main()
Dim test As New TestClass
Dim propNames As New List(Of String)(New String() {"testprop", "testProp", "Testprop", "TestProp"})
'Sanity Check
System.Console.WriteLine(test.testprop)
System.Console.WriteLine(test.testProp)
System.Console.WriteLine(test.Testprop)
System.Console.WriteLine(test.TestProp)
For Each propName As String In propNames
Dim propInfo As PropertyInfo = test.GetType().GetProperty(propName, BindingFlags.Public Or BindingFlags.Instance)
If propInfo Is Nothing Then
System.Console.WriteLine("Uh oh! We don't have PropertyInfo for {0}", propName)
Else
System.Console.WriteLine("Alright, we have PropertyInfo for {0} and its value is: {1}", propName, propInfo.GetValue(test, Nothing))
End If
Next
End Sub
Public Class TestClass
Private _testProp As String = "I got it!"
Public Property TestProp() As String
Get
Return _testProp
End Get
Set(ByVal value As String)
_testProp = value
End Set
End Property
End Class
End Module
令我十分惊讶的是,输出结果如下:
I got it! I got it! I got it! I got it! Uh oh! We don't have PropertyInfo for testprop Uh oh! We don't have PropertyInfo for testProp Uh oh! We don't have PropertyInfo for Testprop Alright, we have PropertyInfo for TestProp and its value is: I got it!
TL;DR
在VB.NET中,变量名通常是不区分大小写的。然而,在类型上调用GetProperty方法时,属性名称似乎是区分大小写的。是否有一种“VB.NET风格”的方式可以忽略大小写来调用此方法?或者我必须采用C#思维方式并关注大小写?
GetProperty()
是 .Net 的,不是 VB。这就是你的问题。 - SLaks