samedi 22 mai 2021

Cast func parameter type to object type

I have the following func:

var instance = new MyInstance();
var method = instance.GetType().GetMethod("MyMethod");
Func<bool, PropertyInfo, string, MyClass, object> myFunc = CreateFunc(instance, method);

private static Func<bool, PropertyInfo, string, MyClass, object> CreateFunc(
    object instance,
    MethodInfo method)
{
    var propertyHandlerInterface = instance.GetType().GetInterface(typeof(IPropertyHandler<>).Name);
    var valueType = propertyHandlerInterface.GetGenericArguments().First();
    var funcType = typeof(Func<,,,,>);
    var type = funcType.MakeGenericType(
        valueType,
        typeof(PropertyInfo),
        typeof(string),
        typeof(MyClass),
        typeof(object));
    return (Func<bool, PropertyInfo, string, MyClass, object>)Delegate.CreateDelegate(
        type,
        instance,
        method);
}

I can call it like this:

var myValue = true;
var result = myFunc(myValue, somePropertyInfo, "some string", someMyClassInstance);

I need to be able to cast the first parameter bool to object so that the func looks like this...

Func<object, PropertyInfo, string, MyClass, object> myFunc = CreateMyFunc();

...so I can call it like this:

object myValue = true; // <-- This is key, myValue is of type object.
var result = myFunc(myValue, somePropertyInfo, "some string", someMyClassInstance);

How would I achieve this?

I understand that I need to do some casting here, maybe with the help of the Expressions API?

return (Func<bool, PropertyInfo, string, MyClass, object>)Delegate.CreateDelegate(
    type,
    instance,
    method)




Aucun commentaire:

Enregistrer un commentaire