[英]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:我正在使用一些遗留的 C# 代码,以下是我无法更改的两个重载方法:
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");
当该代码传递除 LegacyData 引用之外的任何内容时,将调用
PerformCheck(object data)
,例如PerformCheck("Hello World");
However, if null is passed, PerformCheck(LegacyData data)
gets invoked.但是,如果通过了
PerformCheck(LegacyData data)
。 Strangely the PerformCheck implementations are different depending on what is passed.奇怪的是,根据传递的内容,PerformCheck 实现是不同的。 I would like the
PerformCheck(null)
to invoke the PerformCheck(object data)
implementation instead.我希望
PerformCheck(null)
改为调用PerformCheck(object data)
实现。 How do I make this work?我该如何进行这项工作?
You can force the behavior by casting null
to anything other than LegacyData
.您可以通过将
null
强制转换为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.这会按预期输出“其他”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.