1

我正在尝试在给定整数参数的情况下动态调用对象上的索引器。例如

Public Class MyC
        Default Public ReadOnly Property Items(index As Integer) As String
            Get
                Return "Integer indexer"
            End Get
        End Property

        Default Public ReadOnly Property items(x As String) As String
            Get
                Return "String indexer"
            End Get
        End Property
End Class

...

dim obj as MyC = new MyC()
dim result as string = obj(10) 'Invoke property without using reflection

如果我想动态调用索引器,而不假设特定的属性名称,并且考虑到索引器可能过载的事实,我可以这样做:

Dim a As Object = obj.GetType().InvokeMember("", Reflection.BindingFlags.GetProperty, Nothing, obj, {10})
Dim b As Object = obj.GetType().InvokeMember("", Reflection.BindingFlags.GetProperty, Nothing, obj, {"str"})

这些行根据我传入的参数数组方便地确定要调用哪个索引器。

现在,如果可能的话,我想通过实际存储属性(作为 PropertyInfo 对象)来提高性能,因此每次调用它时都不必重新计算属性。

有没有办法检索默认成员索引器的特定重载并实际存储该方法而不调用它?

4

1 回答 1

1
Dim obj = new MyC()

' Get all default members
Dim defaultmembers = obj.GetType().GetDefaultMembers().Cast(Of PropertyInfo)()

' Get the 'Int32' overload the hard way
Dim intIndex = defaultmembers.Single(Function(m) m.GetGetMethod().GetParameters().Single().ParameterType = GetType(Integer))

' Get the 'String' overload the easy way :-)
Dim stringIndex = defaultmembers.Single(Function(m) m.ToString().Contains("[System.String]"))

' create delegates
Dim intFunc As Func(Of Int32, String) = System.Delegate.CreateDelegate(GetType(Func(Of Int32, String)), obj, intIndex.GetGetMethod())
Dim strFunc As Func(Of String, String) = System.Delegate.CreateDelegate(GetType(Func(Of string, String)), obj, stringIndex.GetGetMethod())

' Now you can call them
Console.WriteLine(intFunc(10))
Console.WriteLine(strFunc("12"))
于 2013-07-30T14:57:39.470 回答