Far*_*yev 5 .net c# generics clr
我必须创建一个方法,用于从具有指定类型的集合中选择firts属性.
我已经创建了这样的方法(为了简洁,我删除了一些部分):
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);
}
Run Code Online (Sandbox Code Playgroud)
我可以将此方法称为:
List<Person> personList = new List<Person>();
// .. initialize personList
personList.AsQueryable()
.SelectFirstPropertyWithType<Person, int>()
.ToList();
Run Code Online (Sandbox Code Playgroud)
一切正常.
但是,我不想将第一个参数类型设置为Person,因为编译器可以从集合的源中推断出这个参数类型.有没有办法像这样调用这个方法:
.SelectFirstPropertyWithType<int>()
问题是我需要T在我的方法中使用参数,而且我不想Func在运行时使用反射创建.
谢谢.