I have a method that is called with an instance of an anonymous type. The type is always the same, but the instance is different.
NOTE: I am passed the anonymous object simply as a type object
.
I know the anonymous type has a property named Request
of type HttpRequestMessage
. Here is my method that is executed with the anonymous type in info.Value
.
void IObserver<KeyValuePair<string, object> event> OnNext(KeyValuePair<string, object> info)
{
HttpRequestMessage request = ?????
}
I can get the property getter like so:
MethodInfo propertyGetter = type.GetProperty("Request").GetGetMethod();
But I can't afford the cost of reflection when reading the property of the instance passed to me.
How can I create a delegate that I pass the instance to and get the property value?
I tried this
private delegate HttpRequestMessage RequestPropertyGetterDelegate(object instance);
private static RequestPropertyGetterDelegate RequestPropertyGetter;
private static RequestPropertyGetterDelegate CreateRequestFromPropertyDelegate(Type type)
{
MethodInfo propertyGetter = type.GetProperty("Request").GetGetMethod();
return (RequestPropertyGetterDelegate)Delegate.CreateDelegate(typeof(RequestPropertyGetterDelegate), propertyGetter);
}
But I am experiencing a binding error
System.ArgumentException: 'Cannot bind to the target method because its signature is not compatible with that of the delegate type.'
Aucun commentaire:
Enregistrer un commentaire