给定以下泛型接口和实现类:
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> {
}在不指定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>();换句话说,可以做些什么来获得类型推断?
谢谢!
发布于 2009-01-28 12:03:26
写写怎么样?
var people = repository.Find<Employee>();它节省了相同的打字量,但方式不同。
发布于 2009-01-28 12:08:47
如果不指定U,我怎么能调用Find方法呢?
你不能这么做。
不幸的是,基于返回值,C#的泛型方法重载解析并不匹配。
请参阅Eric Lippert的博客文章:C# 3.0 Return Type Inference Does Not Work On Method Groups
但一种简单的编写方法是使用var关键字。
var employees = repository.Find<Employee>();https://stackoverflow.com/questions/487373
复制相似问题