我试图理解为什么我不能从对象返回一个方法作为Func<>函数的泛型,但另一方面,我可以Func<>通过参数传递与泛型相同的方法。
请分析以下例子:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
MethodDoSth3可以正确传递Foo1.Retrieve和Foo2.Getto DoSth,但我不能像在 method 中那样编写代码DoSth2,因为它不会编译。
我想了解为什么DoSth2不正确以及我如何纠正它以便能够通过 generic 返回方法集合Func<>。
看编译错误:
错误 CS0407:“SomeDto1 Foo1.Retrieve(int)”的返回类型错误
编译器知道Foo1.Retrieve返回一个SomeDto1. 但是,该方法DoSth2应该Func<int, T> 为 anyT返回 a 。你可以调用DoSth<string>(),它应该返回一个Func<int, string>s的集合。但是,SomeDto显然不是string,所以这显然是不可能的。