0

我正在尝试DateTime通过反射检索一个。该值不在类或静态类中,而是来自lambda expression...

我有这个非常简单的 lambda 表达式:ATest => ATest.MyDate == DateTime.Now

现在,通过ExpressionVisitor我正在尝试获取日期时间值:

public class ExpressionComparionsVisitor : ExpressionVisitor
{
    public Expression Modify(Expression expression)
    {
        return base.Visit(expression);
    }


    protected override Expression VisitMember(MemberExpression node)
    {
        if (node.NodeType == ExpressionType.MemberAccess)
        {
            if (node.Member.MemberType == System.Reflection.MemberTypes.Field)
            {
                if (node.Type ==  typeof(DateTime))
                {
                    System.Reflection.FieldInfo fieldInfo = node.Member as System.Reflection.FieldInfo;

                    if (fieldInfo != null)
                    {
                        //Here what I have tried, but no success

                        //var n = (DateTime)fieldInfo.GetValue(fieldInfo);
                        //var n = (DateTime)fieldInfo.GetValue(typeof(DateTime));
                        //var n = (DateTime)fieldInfo.GetValue(node.Member);
                        //var n = (DateTime)fieldInfo.GetValue(null);
                    }
                }
            }
        }
            return base.VisitMember(node);
    }
}

如何获取该字段的 DateTime 值?谢谢

4

1 回答 1

0

简而言之,你不能。您的 lambdaATest => ATest.MyDate == DateTime.Now表示一个函数,该函数接受参数 ( ATest) 并根据与 的相等性返回布尔ATest.MyDate值,因此对于不同的提供的输入DateTime.Now,值可以不同。ATest.MyDate要获得一些具体的价值,您需要提供一些具体的输入:

class MyClass {public DateTime MyDate;}

var someVal = new MyClass { MyDate = new DateTime(2020, 01, 01) };
Expression<Func<MyClass, bool>> expr = ATest => ATest.MyDate == DateTime.Now;
var node = (expr.Body as BinaryExpression).Left as MemberExpression;
var fi = node.Member as FieldInfo;
Console.WriteLine(fi.GetValue(someVal)); // prints 1 January of 2020 in corresponding format
于 2020-06-18T23:35:26.857 回答