gpt4 book ai didi

c# - 动态声明 Func

转载 作者:太空狗 更新时间:2023-10-29 20:57:35 24 4
gpt4 key购买 nike

考虑一下:

var propertyinfo = typeof(Customer).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;

现在我要声明

Func<int,orderType>

我知道这是不可能的,因为 ordertype 在运行时,但是有什么解决方法吗?

这正是我想要做的:

var propertyinfo = typeof(T).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;

var param = Expression.Parameter(typeof(T), "x");
var sortExpression = (Expression.Lambda<Func<T, orderType>>
(Expression.Convert(Expression.Property(param, sortExpressionStr), typeof(orderType)), param));

这一切都是因为我想转换:

Expression<Func<T,object>> to Expression<Func<T,orderType>>

或者如果不可能,那么我想从一开始就用正确的类型创建它,情况如下:

我在一个方法中,它有一个 type(Customer) 和一个我想按它排序的类型的属性名称,我想创建一个排序表达式树来将它传递给 Orderby(此处)。

最佳答案

您可以通过使用开放的泛型类型定义,然后从中创建特定类型来做到这一点:

typeof(Func<,>).MakeGenericType(typeof(int), orderType);

但是,您尝试执行的操作(调用 Lambda<TDelegate> )并非直接可行。您必须调用 Lambda没有类型参数:

var propertyinfo = typeof(T).GetProperty(sortExpressionStr);
Type orderType = propertyinfo.PropertyType;

var param = Expression.Parameter(typeof(T), "x");
var sortExpression = Expression.Lambda(
Expression.Convert(Expression.Property(param, sortExpressionStr),
orderType),
param));

这将创建适当的 Func<,>为你在幕后。如果你想编译表达式并使用委托(delegate),你只能动态地使用

sortExpression.Compile().DynamicInvoke(param);

如果你想调用OrderBy Queryable 上的扩展方法,事情变得有点复杂:

var propertyInfo = typeof(T).GetProperty(sortExpressionStr);
Type orderType = propertyInfo.PropertyType;

// first find the OrderBy method with no types specified
MethodInfo method = typeof(Queryable).GetMethods()
.Where(m => m.Name == "OrderBy" && m.GetParameters().Length == 2)
.Single();
// then make the right version by supplying the right types
MethodInfo concreteMethod = method.MakeGenericMethod(typeof(T), orderType);

var param = Expression.Parameter(typeof(T), "x");

// the key selector for the OrderBy method
Expression orderBy =
Expression.Lambda(
Expression.Property(orderParam, propertyInfo),
orderParam);

// how to use:
var sequence = new T[0].AsQueryable(); // sample IQueryable

// because no types are known in advance, we need to call Invoke
// through relection here
IQueryable result = (IQueryable) concreteMethod.Invoke(
null, // = static
new object[] { sequence, orderBy });

关于c# - 动态声明 Func<in T, out Result>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3752305/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com