为什么无法为泛型Func <>分配方法

I'm trying to understand why I can't return a method from object as a generic Func<> from a function, but on the other hand, I can pass the same method as a generic Func<> via parameters.

请分析以下示例:

public class SomeDto1
{
}

public class SomeDto2
{
}

public class Foo1
{
  public static SomeDto1 Retrieve(int number)
  {
    // do sth with number
    return new SomeDto1();
  }
}

public class Foo2
{
  public static SomeDto2 Get(int number)
  {
    // do sth with number
    return new SomeDto2();
  }
}

public class DoSthWithMethods
{
  private void DoSth<T>(Func<int, T> method)
  {
    var dto = method(16);
    // do sth with dto
  }

  public IEnumerable<Func<int, T>> DoSth2<T>()
  {
    // this is not legal
    yield return Foo1.Retrieve;
    yield return Foo2.Get;
  }

  public void DoSth3()
  {
    // this is legal
    DoSth(Foo1.Retrieve);
    DoSth(Foo2.Get);
  }
}

Method DoSth3 can correctly pass Foo1.Retrieve and Foo2.Get to DoSth, but I can't write code like in method DoSth2, because it wouldn't compile.

I want to understand why DoSth2 is incorrect and how possibly I can correct it to be able to return the collection of methods via generic Func<>.

评论
  • xet
    xet 回复

    查看编译器错误:

    错误CS0407:“ SomeDto1 Foo1.Retrieve(int)”具有错误的返回类型

    The compiler knows that Foo1.Retrieve returns a SomeDto1. However, the method DoSth2 is supposed to return a Func<int, T> for any T. You could call DoSth<string>(), and it's supposed to return a collection of Func<int, string>s. However, SomeDto is obviously not a string, so this is obviously not possible.