与泛型类型和表达式的协方差

时间:2013-09-13 12:59:34

标签: c# c#-4.0 generics covariance

我正在尝试在我的程序中使用协方差,但是当我在我的方法中使用Expression<Func<T>>作为参数时,我收到以下错误

  

参数必须是输入安全的。方差无效   Type参数T必须在Expression <TDelegate>

上保持有效

有没有办法使用expresssion作为方法中的参数以及协方差?

以下示例

class Program
    {
        static void Main(string[] args)
        {
            var temp = new Temp<People>();
            TestMethod(temp);

        }

        public static void TestMethod(ITemp<Organism> param)
        {

        }
    }

    class Temp<T> : ITemp<T>
        where T : Organism
    {
        public void Print() {}

        public void SecondPrint(Expression<Func<T>> parameter) {}
    }


    class People : Organism {}
    class Animal : Organism {}
    class Organism {}

    interface ITemp<out T> where T : Organism
    {
        void SecondPrint(Expression<Func<T>> parameter);
    }

1 个答案:

答案 0 :(得分:0)

请参阅此Eric Lippertanswer

  

“out”表示“T仅用于输出位置”。您正在输入位置使用它

(即使它是Func委托的返回类型)。如果编译器允许,您可以编写(在您的示例中):

static void Main(string[] args)
{
    var temp = new Temp<People>();
    TestMethod(temp);
}

public static void TestMethod(ITemp<Organism> param)
{
    param.SecondPrint(() => new Animal());
}

SecondPrint上调用Temp<People>,但传递返回Animal的lambda。

我会删除T上的方差注释:

interface ITemp<T> where T : Organism
{
    void SecondPrint(Expression<Func<T>> parameter);
}

并在TestMethod中使T参数化:

public static void TestMethod<T>(ITemp<T> param) where T : Organism
{
}