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

时间:2023-01-31 16:13:11

Given the following generic interface and implementing class:

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

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> {

}

How could I call the Find method without specififying U?

如何在不指定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>();

In other words, what can be done to get type inference?

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

Thanks!

2 个解决方案

#1


How about writing

写作怎么样

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

It's saving the same amount of typing but in a different way.

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

#2


How could I call the Find method without specififying U?

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

You can't.

Unfortunately C#'s generic method overload resolution doesn't match based on return values.

不幸的是,C#的泛型方法重载决策根据返回值不匹配。

See Eric Lippert's blog post about it: C# 3.0 Return Type Inference Does Not Work On Method Groups

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

But one easy way to write this is using var keyword.

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

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

#1


How about writing

写作怎么样

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

It's saving the same amount of typing but in a different way.

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

#2


How could I call the Find method without specififying U?

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

You can't.

Unfortunately C#'s generic method overload resolution doesn't match based on return values.

不幸的是,C#的泛型方法重载决策根据返回值不匹配。

See Eric Lippert's blog post about it: C# 3.0 Return Type Inference Does Not Work On Method Groups

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

But one easy way to write this is using var keyword.

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

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