我必须创建一个方法来从具有指定类型的集合中选择第一个属性。
我创建了这样的方法(为简洁起见,我删除了一些部分):
public static IQueryable<TResult> SelectFirstPropertyWithType<T, TResult>(this IQueryable<T> source)
{
// Get the first property which has the TResult type
var propertyName = typeof(T).GetProperties()
.Where(x => x.PropertyType == typeof(TResult))
.Select(x => x.Name)
.FirstOrDefault();
var parameter = Expression.Parameter(typeof(T));
var body = Expression.Convert(Expression.PropertyOrField(parameter, propertyName), typeof(TResult));
var expression = Expression.Lambda<Func<T, TResult>>(body, parameter);
return source.Select(expression);
}
我可以将此方法称为:
List<Person> personList = new List<Person>();
// .. initialize personList
personList.AsQueryable()
.SelectFirstPropertyWithType<Person, int>()
.ToList();
一切正常。
但是,我不想将第一个参数类型设置为 Person
,因为编译器可以从集合的来源推断出这个参数类型。有没有办法像这样调用方法:
.SelectFirstPropertyWithType<int>()
问题是我需要T
我的方法中的参数,我不想创建 Func
在运行时进行反射。
谢谢。
最佳答案
没有。编译器应该能够推断所有 类型参数。如果不能,它将要求您指定所有这些。
编译器无法告诉您它可以推断出第一个或第二个,因此它不会有一个不确定的编译应用程序,而是会中断。
关于c# - 在泛型方法中仅设置第二个参数类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30908109/