【问题标题】:Covariance with generic type and expression与泛型类型和表达式的协变
【发布时间】:2013-09-18 04:17:02
【问题描述】:

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

参数必须是输入安全的。方差无效。
类型参数 T 必须在 Expression <TDelegate> 上始终有效

有没有办法在方法中使用表达式作为参数以及协方差?

以下示例

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);
    }

【问题讨论】:

    标签: c# c#-4.0 generics covariance


    【解决方案1】:

    看到这个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());
    }
    

    Temp&lt;People&gt; 上调用SecondPrint,但传递一个返回Animal 的lambda。

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

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

    并在T 中设置TestMethod 参数:

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

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-24
      • 1970-01-01
      相关资源
      最近更新 更多