Cannot convert type via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion

前端 未结 3 734
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-07 23:14

In C#, if I have a parameter for a function where the parameter type is of an interface, how do a pass in an object that implements the interface.

Here is an example

3条回答
  •  情书的邮戳
    2021-01-08 00:00

    In additional to List.Cast, C#'s generics provide a good support for Covariance and contravariance. This example causes it to work in the way I think you originally intended.

    public class Program
    {
        public static void Main()
        {
             Foo(new List());
        }
    
        public static void Foo(List bar) where T : IFim
        {
            throw new NotImplementedException();
        }
    
        public class IFim{}
        public class Fim : IFim{}
    }
    

提交回复
热议问题