C#类型推断泛型方法类型参数,其中方法没有参数

Mic*_*out 7 c# generics type-inference

给定以下通用接口和实现类:

public interface IRepository<T> {
    // U has to be of type T of a subtype of T
    IQueryable<U> Find<U>() where U : T;
}

public class PersonRepository : IRepository<Employee> {

}
Run Code Online (Sandbox Code Playgroud)

如何在不指定U的情况下调用Find方法?

var repository = new EmployeeRepository();
// Can't be done
IQueryable<Employee> people = repository.Find();

// Has to be, but isn't Employee a given in this context?
IQueryable<Employee> people = repository.Find<Employee>();

// Here I'm being specific
IQueryable<Manager> managers = repository.Find<Manager>();
Run Code Online (Sandbox Code Playgroud)

换句话说,可以做些什么来获得类型推断?

谢谢!

Pop*_*lin 15

如何在不指定U的情况下调用Find方法?

你不能.

不幸的是,C#的泛型方法重载决策基于返回值不匹配.

请参阅Eric Lippert关于它的博文: C#3.0返回类型推断在方法组上不起作用

但是写一个简单的方法就是使用var关键字.

var employees = repository.Find<Employee>();
Run Code Online (Sandbox Code Playgroud)


Ada*_*lph 6

写作怎么样?

var people = repository.Find<Employee>();
Run Code Online (Sandbox Code Playgroud)

它以不同的方式节省了相同的打字量.