简体   繁体   中英

Why do I get the following error? Invalid variance modifier. Only interface and delegate type parameters can be specified as variant

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

namespace Variance

{
  class A { }

  class B : A { }

  class C<out T>  { }

class Program
{
    static void Main(string[] args)
    {
        var v = new C<B>();

        CA(v);
    }

    static void CA(C<A> v) { }
  }
}

This is the offending line:

class C<out T> 

As the error message tells you, you can't apply generic variance to classes, only to interfaces and delegates. This would be okay:

interface C<out T>

The above is not.

For details, see Creating Variant Generic Interfaces

You're attempting to apply generic variance to a class. This is not supported. It is only supported on interfaces and delegate types.

Illegal:

class C<out T>  { }

Legal:

interface C<out T> {}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM