简体   繁体   中英

System.ArgumentNullException when creating a call expression on Xname.Get

I am trying to create a dynamic query on a XElement source by using expression trees. A part of this query needs to compare the value of an XElement Attribute and it is when constructing the expressions for obtaining the attribute value I am getting the ArgumentNullException. It is connected to the Expression.Call for XName.Get but I do not know how to interpret the exception in for this case.

PS: the constant expressions in the code are there just for this example.

The code:

var value = 
            Expression.Property(
                Expression.Call(Expression.Parameter(typeof(XElement), "attr1"), typeof(XElement).GetMethod("Attribute"), 
                    Expression.Call(typeof(XName).GetMethod("Get", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly), Expression.Constant("id"))), 
            "Value");
typeof(XName).GetMethod(
    "Get", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)

This is your problem, as PetSerAl already pointed out. But removing BindingFlags.Instance won't solve anything, you need to specify that you want a static method:

typeof(XName).GetMethod(
    "Get", BindingFlags.Static | BindingFlags.Public | BindingFlags.DeclaredOnly)

This still won't work, it throws AmbiguousMatchException , but we're getting closer. Your Call has a single string parameter, so we need to specify we want that overload of XName.Get :

typeof(XName).GetMethod("Get", new[] { typeof(string) })

(We don't need to specify BindingFlags , because the default works fine.)

With this modification, your snippet seems to work fine.

I can only guess, because this expression tree as shown isn't compilable.

The problem is probably because of your Expression.Parameter call. Parameters must be reference equal to whatever is passed in. The descriptive name ("attr1") is only for debugging purposes.

If that doesn't solve your problem, then please post the full tree (or at least more of it).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM