Delegate.CreateDelegate without prototype

I have to do it now

private delegate void set(int obj); //declare the prototype

...
Delegate delegate1 = Delegate.CreateDelegate(typeof(set), new testObject(), props[0].GetSetMethod());

((set)delegate1)(1);

      

Is there a way to CreateDelegate without this prototype and call it any parameter? GetSetMethod () returns a very specific MethodInfo that takes a specific type as an argument.

thank

+2


source to share


1 answer


In .NET 3.5, you can use Expression.GetActionType

:

    Type setterType = Expression.GetActionType(props[0].PropertyType);
    Delegate delegate1 = Delegate.CreateDelegate(setterType,
        new testObject(), props[0].GetSetMethod()
    );

      

Or if you want to open a delegate (i.e. some instance testObject

not tied to a new one):



    Type setterType = Expression.GetActionType(
        props[0].DeclaringType, props[0].PropertyType);
    Delegate delegate1 = Delegate.CreateDelegate(setterType,
        null, props[0].GetSetMethod()
    );

      

Nevertheless; note that you will have to use these delegates via DynamicInvoke

, which is much slower than using a fully typed delegate via Invoke

.

Another option (for this scenario) is to bind to a delegate that accepts object

and use casting inside the delegate - perhaps with fantastic generics , compiled Expression

or custom IL.

+2


source







All Articles