简体   繁体   中英

C# pass a null value as a generic object rather than a type for overloaded methods

I'm working with some legacy C# code and below are two overloaded methods that I can't change:

void PerformCheck(LegacyData data) {...}
void PerformCheck(object data) {...}

There is some code that uses the above overloaded methods. When that code passes anything but a LegacyData reference, the PerformCheck(object data) gets invoked, eg PerformCheck("Hello World"); However, if null is passed, PerformCheck(LegacyData data) gets invoked. Strangely the PerformCheck implementations are different depending on what is passed. I would like the PerformCheck(null) to invoke the PerformCheck(object data) implementation instead. How do I make this work?

You can force the behavior by casting null to anything other than LegacyData .

var x = new Test();
x.PerformCheck((object)null);

public class Test
{
    public void PerformCheck(LegacyData data) { Console.WriteLine("legacy"); }
    public void PerformCheck(object data) { Console.WriteLine("other"); }
}
    
public class LegacyData {}

This outputs "other" as expected.

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