在运行时使用 ref 参数创建 C# 委托类型 [英] Create C# delegate type with ref parameter at runtime
问题描述
我需要在运行时创建一个带有 ref
参数的委托类型.
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);
该类型 td
用于创建 C#4 表达式树,编译成委托.
That type td
is used to create a C#4 expression tree, which is compiled into a delegate.
由于我的表达式树中的代码修改了参数s
,所以我需要通过引用传递s
.
Since the code in my expression tree modifies the parameter s
, I need to pass s
by reference.
我必须支持任何类型 S
,所以我不能使用显式委托类型声明,因为我只有 Type ts = typeof (S)
及其ref
类型 Type tsr = ts.MakeByRefType ()
.
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 ()
.
我尝试使用 Expression.GetActionType (tsr)
,但它不允许 ref
类型.
I tried to use Expression.GetActionType (tsr)
, but it does not allow ref
types.
如何在运行时使用 ref
参数构建委托?
How do I build a delegate with ref
parameters at runtime ?
推荐答案
在 .NET 4 中,您可以使用 Expression.GetDelegateType
方法.与 GetActionType
不同,它适用于 ByRef
类型.
In .NET 4, you can use the Expression.GetDelegateType
method. Unlike GetActionType
, it works fine with ByRef
types.
例如:
// void MyDelegate(ref int arg)
var delType = Expression.GetDelegateType(typeof(int).MakeByRefType(),
typeof(void));
如果您使用的是 .NET 3.5,则此方法不可用.如果你想复制它的功能,我建议看看它的实现(使用反编译器).它没有太多的依赖关系;这绝对是可行的.
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.
这篇关于在运行时使用 ref 参数创建 C# 委托类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!