简体   繁体   中英

Possible to differentate between nothing passed, or one null passed to F(params String[] values)?

I have a function

public List<Item> Filter(params String[] valuesOrdered)
{
    //...
}

which acts as a filter on all Item s.

public class Item
{
    List<String> propertiesOrdered;
    //...
}

So that if I call eg Filter("prop1") , then all Item s with "prop1" as the first entry their properties will be matched.

If I call Filter() , then all Item s should be returned.

I also need to be able to match on null values. So for instance right now I can call Filter(null, null) and all Item s with null, null as their first properties will be matched.

All of this works except when I call Filter(null) . It will be interpreted the same way as Filter() , but the intention is that the former should return all Item s with null as their first property, and the latter should return all Item s.

I tried defining an overload to deal with this

public List<Item> Filter(String value)
{
    if(value == null)
        return Filter(new String[] {null});
    else
        return Filter(value);
}

But the compiler just shows an Ambiguous Invocation error when I call Filter(null) .

If you drop the overload, then this:

Filter(null);

will be called as this:

string[] valuesOrdered = null;
Filter(valuesOrdered);

and not like this:

Filter(new string[] { null });

So, you can detect this, and if you want it to behave as though you passed an array containing a single null , then this will suffice:

public List<Item> Filter(params String[] valuesOrdered)
{
    valuesOrdered = valuesOrdered ?? new string[] { null };

    //...
}

Note that this:

Filter();

will in fact be called as this:

Filter(new string[0]);

so there is a difference between the two that you can detect.

Here's a simple LINQPad program that demonstrates:

void Main()
{
    Filter();
    Filter(new[] { "a" });
    Filter("a");
    Filter(null);
}

public static void Filter(params string[] values)
{
    values.Dump();
}

output:

LINQPad输出

You can use the syntax

Filter((String)null)

to call the method in its "expanded" form with a length-one array.

If that syntax is unpleasant to you, you might want to define a constant

const String NullStr = null;

and use

Filter(NullStr)

instead.

PS! Personally I prefer string over String but I stuck to your convention here since it was not relevant to your question.

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