Create C# delegate type with ref parameter at runtime

故事扮演 提交于 2019-12-09 07:51:42

问题


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.



来源:https://stackoverflow.com/questions/5570328/create-c-sharp-delegate-type-with-ref-parameter-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!