【发布时间】:2020-05-07 15:05:18
【问题描述】:
我想在表达式中记录实际值,而不是对表达式中使用的属性/字段/常量的引用。我在这里有一个小提琴:https://dotnetfiddle.net/7SNxAq 其代码(为后代)是:
using System;
using System.Linq.Expressions;
public class Program
{
public static void Main()
{
var input = new Foo
{
Shape = "Sphere",
SizeType = SizeType.Small
};
Expression<Func<Foo, bool>> expression = f =>
f.Hue == Constants.Hues.Red &&
f.Shape == input.Shape &&
f.Size == input.SizeType.ToString() &&
!f.IsDeleted;
Console.WriteLine(expression);
}
}
internal class Foo
{
public string Hue { get; set; }
public string Shape { get; set; }
public bool IsDeleted { get; set; }
public string Size { get; set; }
public SizeType SizeType { get; set; }
}
internal enum SizeType
{
Small, Medium, Large
}
internal class Constants
{
public class Hues
{
public static string Red = "#f00";
}
}
Console.WriteLine(expression) 的结果是:
f => ((((f.Hue == Hues.Red) AndAlso (f.Shape == value(Program+<>c__DisplayClass0_0).input.Shape)) AndAlso (f.Size == value(Program+<>c__DisplayClass0_0).input.SizeType.ToString())) AndAlso Not(f.IsDeleted))
但我希望看到这样的东西
f => ((((f.Hue == Hues.Red) AndAlso (f.Shape == "Sphere")) AndAlso (f.Size == "Small")) AndAlso Not(f.IsDeleted))
这可以做到吗,还是我错过了表达的重点?
【问题讨论】:
-
你的表达即将结束
input。为什么不传入第二个Foo并在表达式中使用它:Expression<Func<Foo, Foo, bool>> -
感谢@Sean 的提示,但这个人为的例子最接近阅读的代码,在这里分享太多了。它也不会“扩展”或“解析”对其值的引用。
标签: c# .net lambda expression