Create C # delegate type with ref parameter at runtime

I need to create a delegate type with a parameter refat runtime.

If I knew the type of the parameter at compile time, I could use an explicit declaration of the delegate type, for example:

// S is some struct / value type, e.g. int or Guid
delegate void VoidDelSRef (ref S s);
Type td = typeof (VoidDelSRef);

This type is tdused to create a C # 4 expression tree that compiles into a delegate.

Since the code in my expression tree changes the parameter s, I need to pass sby reference.

I need to support any type s, so I cannot use an explicit declaration of the delegate type, because I only have Type ts = typeof (S)its reftype Type tsr = ts.MakeByRefType ().

I tried to use Expression.GetActionType (tsr), but does not allow types ref.

How to create a delegate with parameters refat runtime?

+2
source share
1 answer

In .NET 4, you can use the method . Unlike , it works great with types . Expression.GetDelegateTypeGetActionTypeByRef

eg:.

// void MyDelegate(ref int arg)
var delType = Expression.GetDelegateType(typeof(int).MakeByRefType(), 
                                         typeof(void));

If you are using .NET 3.5, this method is not available. I recommend taking a look at its implementation (with a decompiler) if you want to reproduce its functionality. He does not have too many dependencies; it is definitely doable.

+2
source

Source: https://habr.com/ru/post/1771667/


All Articles