Note that there are some explanatory texts on larger screens.

plurals
  1. POHow can I create delegates to a property of unknown type?
    primarykey
    data
    text
    <p>I'm using reflection to access an object's properties by name, to call the get method. This is a relatively slow operation over thousands of iterations, even when I cache the PropertyInfo for each property. I'm trying to come up with something faster using delegates, but VB.Net won't allow me to call CreateDelegate on an object without knowing the return type of the property at compile time. How can I do this?</p> <ul> <li>I access properties via their (string) name</li> <li>The return type of the property is unknown at compile time</li> <li>I'm trying to create a delegate to quickly access one or more properties on thousands of instances of an object</li> </ul> <p>Edit: Code follows</p> <p>testC is an example object which contains the properties I'm acessing by name. del is the delegate I want to use to call the property on an instance of testC.</p> <pre><code>Public Class testC Public Property prop1 As String Public Property prop2 As Double Public Property prop3 As Integer Public Property prop4 As String Public Property prop5 As String Public Property prop6 As String End Class Public Delegate Function del() As Object </code></pre> <p>The first time I access each property, I use reflection to get the property from it's name, and attempt to build a delegate to quickly access it on other instances of the object in the future.</p> <pre><code>Dim pi As Reflection.PropertyInfo = obj.GetType().GetProperty(propName) Dim myDelegate As Object = System.Delegate.CreateDelegate(GetType(del), pi.GetGetMethod()) </code></pre> <p>Calling CreateDelegate throws this exception:</p> <blockquote> <p>System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.</p> </blockquote>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload