我如何解决 .NET 2 上 Action 的协方差问题?

How can I this fix covariance issue with Action on .NET 2?

我需要使用一种方法创建一个协变接口,该方法采用带有协变泛型参数的委托。这是问题中的代码示例:

interface IExample<out T1>
{
    void ExampleMethod(Action<T1> someAction);
}

在 Mono/.NET 4 配置文件上编译正常(在 Xamarin studio 中测试)。但是,在 .NET 2 上(由于我使用的是 Unity 游戏引擎,我不得不使用它),我收到以下错误:

error CS1961: The covariant type parameter 'T1' must be invariantly valid on `CovarianceExample.IExample.ExampleMethod(System.Action)'

为什么早期的.Net版本会出现这个错误?我该如何解决?

Why does this error occur in early .Net versions?

因为 Action 在 .NET 2.0(或 3.5)中不是逆变的。

How can I fix it?

不要使用 .NET 2.0 :) 我认为现代版本的 Unity 无论如何都是基于更新版本的 Mono - 也许可以升级?

或者,您可以声明自己的 ContravariantAction 委托:

public delegate void ContravariantAction<in T>(T value);

我没有尝试针对 .NET 2.0 这样做,但我相信适当的属性已经存在,并且至少 MS .NET 实现支持泛型变体——它只是没有在 C# 中公开或在BCL.