Guedez
Guedez

Reputation: 197

How to create a delegate for a generic method that requires casting back and forth

I have a method:

MyMethod<T>(T) where T: struct, MyInterface

I have a target delegate as:

public delegate void MyDelegate(object myObject)

I have a collection of Types that are both structs and implement MyInterface

So invoking MyMethod is as simple as:

myMethodInfo.MakeGenericMethod(myType).Invoke(target, new object[]{myObject})

that is, because Invoke accepts object and does the casting for me somewhere in the internal code.

The issue is that I can't seem to make a delegate like MyDelegate(object) because object is not struct, MyInterface

I get why

(MyDelegate)addComponentData.MakeGenericMethod(MyType).CreateDelegate(typeof(MyDelegate), target)

does not work, but I have no idea how to solve it

The reason I need this is because every time I am using any of these objects, I am using them as MyInterface, I have no idea which type they are, only that they implement MyInterface and are structs, therefore they are eligible for the method I need to invoke them on. To make all of this reflection faster, I want to use CreateDelegate, as it seems it is only twice as slow as an actual normal invocation of the method where MethodInfo.Invoke is 100 times slower (source: Is the use of dynamic considered a bad practice?)

Upvotes: 1

Views: 285

Answers (2)

David Browne - Microsoft
David Browne - Microsoft

Reputation: 88852

The only point of using a struct generic method constraint is to avoid boxing. You aren't avoiding boxing. So just declare the method as:

MyMethod(MyInterface obj)

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100527

Make wrapper method that takes an object and use it to construct delegate:

public void Wrapper<T>(object s) where T : struct, MyInterface
{
    MyMethod<T>((T)s);
}

Upvotes: 1

Related Questions