Create C# delegate type with ref parameter at runt

2020-06-07 03:27发布

问题:

I need to create a delegate type with a ref parameter at runtime.

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

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

That type td is used to create a C#4 expression tree, which is compiled into a delegate.

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

I have to support any type S, so I can't use an explicit delegate type declaration, because I only have Type ts = typeof (S) and its ref type Type tsr = ts.MakeByRefType ().

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

How do I build a delegate with ref parameters at runtime ?

回答1:

In .NET 4, you can use the Expression.GetDelegateType method. Unlike GetActionType, it works fine with ByRef types.

E.g.:

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

If you are on .NET 3.5, this method is not available. I recommend taking a look at its implementation (with a decompiler) if you want to replicate its functionality. It doesn't have too many dependencies; it's definitely doable.