C#泛型方法类型参数的类型推断,当方法没有参数时

7

假设有以下通用接口和实现类:

```java public interface MyInterface { public void doSomething(T t); } public class MyImplementation implements MyInterface { public void doSomething(String s) { System.out.println("Doing something with " + s); } } ```
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>();

换句话说,如何进行类型推断?谢谢!
2个回答

15
我该如何在不指定U的情况下调用Find方法? 很遗憾,C#的泛型方法重载解析无法基于返回值进行匹配。
请参阅Eric Lippert关于此问题的博客文章: C#3.0返回类型推断不适用于方法组 但是,一种简单的编写方法是使用var关键字。
var employees = repository.Find<Employee>();

6

如何写作

var people = repository.Find<Employee>();

这是以不同的方式节省相同数量的打字。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接