当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - Building expression to check for null

问题描述:

I'm having trouble to figure out how to build an expression tree to determine if a property is null. I've got something like this:

public static Expression<Func<S, bool>> CreateFunc(QueryPiece<S> queryPc)

{

//arg

ParameterExpression argParam = Expression.Parameter(typeof(S));

//property

MemberExpression memberExpr = Expression.Property(argParam, "SomeProperty");

//property type for constant conversion

Type propType = memberExpr.Member is MethodInfo

? ((MethodInfo)memberExpr.Member).ReturnType

: ((PropertyInfo)memberExpr.Member).PropertyType;

//tried this ... unsuccessfully

Expression func = Expression.Equal(memberExpr, Expression.Constant(null, propType));

return Expression.Lambda<Func<S, bool>>(func, argParam);

}

My hope - however vain ;-) - was that I could just as if the member property was equivalent to null.

I've seen some mentions of how this might be accomplished using Expression.Coalesce, but I can't seem to get it to work. For the record, the runtime error thrown when I try to use the returned Lambda is a generic ArgumentNullException.

I've found this similar post: In C#, how can i add a null check into dynamic express code - I just can't seem to out how to refactor it for my scenario.

分享给朋友:
您可能感兴趣的文章:
随机阅读: