如何使表达式将值类型视为引用类型? [英] How to make expression treat value type as a reference type?
问题描述
我想存储访问对象属性的表达式集合。例如:
I wanted to store a collection of expressions accessing object's properties. For example:
class Entity
{
public int Id { get; set; }
public Entity Parent { get; set; }
public string Name { get; set; }
public DateTime Date { get; set; }
public decimal Value { get; set; }
public bool Active { get; set; }
}
static void Main(string[] args)
{
var list = new List<Expression<Func<Entity, object>>>();
list.Add(e => e.Id);
list.Add(e => e.Name);
list.Add(e => e.Parent);
list.Add(e => e.Date);
list.Add(e => e.Value);
list.Add(e => e.Active);
StringBuilder b = new StringBuilder();
list.ForEach(f => b.AppendLine(f.ToString()));
Console.WriteLine(b.ToString());
Console.ReadLine();
}
此代码输出:
e => Convert(e.Id)
e => e.Name
e => e.Parent
e => Convert(e.Date)
e => Convert(e.Value)
e => Convert(e.Active)
它添加转换
到值类型。
至于我想用LINQ to SQL使用这些表达式,我不需要这样的在表达式中转换
,以便他们成功翻译成SQL。
As far as in the end I wanted to use those expressions with LINQ to SQL, I need not to have that Convert
in expressions, for them to be successfully translated to SQL.
如何实现?
PS:此集合的表达式后来被用作 OrderBy
和 ThenBy
方法的参数。 / p>
P.S.: expressions from this collection are later used as arguments to OrderBy
and ThenBy
methods.
推荐答案
如果您在proeprty类型中创建一个泛型函数,可以避免转换:
If you create a function generic in the proeprty type you can avoid the Convert:
private static LambdaExpression GetExpression<TProp>
(Expression<Func<Entity, TProp>> expr)
{
return expr;
}
那么您可以更改列表的类型
:
then you can change the type of list
:
var list = new List<LambdaExpression>();
list.Add(GetExpression(e => e.Id));
list.Add(GetExpression(e => e.Name));
这将需要您创建您的 OrderBy
和 ThenBy
表达式使用反射例如
This will require you to create your OrderBy
and ThenBy
expressions using reflection e.g.
LambdaExpression idExpr = list[0];
Type keyType = idExpr.ReturnType;
var orderByMethod = typeof(Queryable).GetMethods()
.Single(m => m.Name == "OrderBy" && m.GetParameters().Length == 2)
.MakeGenericMethod(typeof(Entity), keyType);
var ordered = (IQueryable<Entity>)
orderByMethod.Invoke(null, new object[] { source, idExpr });
这篇关于如何使表达式将值类型视为引用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!