在运行时使用ref参数创建C#委托类型 [英] Create C# delegate type with ref parameter at runtime

查看:466
本文介绍了在运行时使用ref参数创建C#委托类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在运行时创建一个带有 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 ,所以我不能使用明确的委托类型声明,因为我只有键入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 metho d。与 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆