通过将扩展方法用作方法参数来推断其扩展类型

时间:2019-06-27 18:08:20

标签: c# .net-core extension-methods type-inference

我试图理解为什么可以在一个实例中推断出泛型类型,而在另一个实例中却无法推断出泛型类型的原因。从对象中返回方法组允许我尝试进行推断,但是使用扩展方法返回方法组可防止推断...请参见下面的“工作”“无效”注释。

错误为The type arguments for the method DoKungFoo<TFoo, TTarget>(Foo<TFoo>) cannot be inferred from the usage

感谢您的输入!


    public class Foo<T>
    {
        public IEnumerable<TTarget> KungFoo<TTarget>(IEnumerable<TTarget> type)
        {
            return type;
        }
    }

    public static class FooExtensions
    {
        public static Func<IEnumerable<TTarget>, IEnumerable<TTarget>> DoKungFoo<TFoo, TTarget>(this Foo<TFoo> foo)
        {
            if(foo == null)
            {
                return null;
            }

            return foo.KungFoo;
        }
    }

    public class Driver()
    {
        public void Test(Foo<Bar> foo)
        {
            //Works
            Bed(foo.KungFoo);

            //Doesn't Work
            Bed(foo.DoKungFoo())
        }

        public void Bed(Func<IEnumerable<Baz>, IEnumerable<Baz>> func)
        {

        }
    }

    public class Bar
    {

    }

    public class Baz
    {

    }

0 个答案:

没有答案
相关问题