Reflection problem within asp user control
Hi,
I have come across a problem when trying to return a property's value
using the PropertyInfo.GetValue method. Hopefully the code below should
help explain...
First I've created a class with a shared property, like this....
Public Class myClass
Public Shared Readonly Property myProperty() As String
Get
Return SomeValue.ToString
End Get
End Property
End Class
Then I've created an ASP usercontrol; and in the codebehind, the PreRender Event looks like this....
Protected Sub Page_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
Dim myString As String = myReflectionFunction(GetType(myClass))
'Some other events happen...
End Sub
.... and the function being called looks like this....
Public Function myReflectionFunction(t As System.Type) As String
Dim pi As Reflection.PropertyInfo = t.GetProperty("myProperty")
Return pi.GetValue(Nothing, Nothing)
End Function
The above code works fine, however; when I change the shared property in myClass to produce different values based on an enum parameter, like this;
Public Class myClass
Public Enum myEnum
Option1
Option2
End Enum
Public Shared Readonly Property myProperty(e As myEnum) As String
Get
If e = myEnum.Option1 Then
Return SomeValue.ToString
Else
Return SomeOtherValue.ToString
End If
End Get
End Property
End Class
... and then adapt the usercontol function to accomodate the parameter....
Public Function myReflectionFunction(t As System.Type) As String
Dim pi As Reflection.PropertyInfo = t.GetProperty("myProperty")
Try
Return pi.GetValue(Nothing, New Object() {myClass.myEnum.Option1}) 'web searches suggest this is the way to do it
Catch ex As Exception
Throw New Exception("Cannot Reflect", ex)
End Try
End Function
... I get a double-error combination.
1. "Exception has been thrown by the target of an invocation."
with an inner exception of....
2. "Parameter count mismatch."
The interesting thing is that the errors don't
get thrown within the Try/Catch block as I would expect, but later on
towards the end of the Page's PreRender event. Stepping through the
code reveals that when executing, the correct value is retrieved by the
reflection.getvalue call. I have no idea why I get this error - any
insight would be very much appreciated.