1

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?)

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Guedez
  • 189
  • 3
  • 14

2 Answers2

1

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);
}
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • the wrapper method will inevitably have to use Invoke, which is 100 times slower than CreateDelegate. If I were to do this, I would just use Invoke – Guedez Aug 30 '19 at 21:36
  • It's calling `Invoke` on the delegate that points to `Wrapper`, not a `MethodInfo`. Big difference. – madreflection Aug 30 '19 at 21:38
  • @Guedez ? why can't you use the same code you had in the question like - `(MyDelegate)methodInfoForWrapper.MakeGenericMethod(MyType).CreateDelegate(typeof(MyDelegate), target)` to create delegate? I'm clearly missed something from your question then - consider to edit the question to clarify restrictions. – Alexei Levenkov Aug 30 '19 at 21:41
  • After some preliminary checks, it seems to be working, I will finish some more tests and mark as the answer – Guedez Aug 30 '19 at 21:57
  • Worked like a charm, funny how a solution so simple slipped past my mind for so long – Guedez Aug 30 '19 at 22:03
0

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)
David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67