如何使用 ByRef 参数在 Action 委托上创建泛型类型?
How to create a generic type on the Action delegate with a ByRef parameter?
我正在尝试在 Action<> 类型上创建一个委托,并将 by-ref 参数作为参数。但我对如何实现这一目标感到困惑。
到目前为止我得到的是:
using System;
class Program
{
struct MyStruct { }
static void FooFn(in MyStruct s) { }
delegate void Foo (in MyStruct s);
public static void Main(string[] args)
{
Foo f = FooFn;
var t1 = typeof(Action<>).MakeGenericType(typeof(MyStruct));
var t2 = typeof(Action<>).MakeGenericType(typeof(MyStruct).MakeByRefType());
var d = Delegate.CreateDelegate(t1, null, f.Method);
}
}
在委托中使用“t1”的问题是签名不匹配。这是一种预期,因为我通过引用传递结构。
t2 也不起作用,因为它抱怨我不能使用 By-ref 参数作为参数列表类型。 :(
在我的例子中,有没有办法用 to Foo 创建委托?还是我 必须 删除 in-modifier?
不,您不能创建带有 by-ref 参数的 Action<T>
,因为该方面是委托签名的一部分,它是预定义的并且在外部你的控制。您必须定义自己的委托类型,就像您对 Foo
所做的那样。此委托类型可以是通用的,但不能声明变体 - 协变和逆变均不与(变体类型的)by-ref 参数兼容。
我正在尝试在 Action<> 类型上创建一个委托,并将 by-ref 参数作为参数。但我对如何实现这一目标感到困惑。
到目前为止我得到的是:
using System;
class Program
{
struct MyStruct { }
static void FooFn(in MyStruct s) { }
delegate void Foo (in MyStruct s);
public static void Main(string[] args)
{
Foo f = FooFn;
var t1 = typeof(Action<>).MakeGenericType(typeof(MyStruct));
var t2 = typeof(Action<>).MakeGenericType(typeof(MyStruct).MakeByRefType());
var d = Delegate.CreateDelegate(t1, null, f.Method);
}
}
在委托中使用“t1”的问题是签名不匹配。这是一种预期,因为我通过引用传递结构。
t2 也不起作用,因为它抱怨我不能使用 By-ref 参数作为参数列表类型。 :(
在我的例子中,有没有办法用 to Foo 创建委托?还是我 必须 删除 in-modifier?
不,您不能创建带有 by-ref 参数的 Action<T>
,因为该方面是委托签名的一部分,它是预定义的并且在外部你的控制。您必须定义自己的委托类型,就像您对 Foo
所做的那样。此委托类型可以是通用的,但不能声明变体 - 协变和逆变均不与(变体类型的)by-ref 参数兼容。