本文介绍了具有可空值类型参数的扩展方法解析的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public static class Extension
{
public static void Test(this DateTime? dt)
{
}
}
void Main()
{
var now = DateTime.Now;
Extension.Test(now); // ok
now.Test(); // compile time error
}
我很好奇,为什么编译器在调用扩展程序时无法解析相同的方法?
I'm just curious, why is the compiler not able to resolve the same method when called as an extension?
推荐答案
DateTime
是无法明确转换为 Nullable<DateTime>
.
C#规范7.6.5.2扩展方法调用:
The C# specification, 7.6.5.2 Extension method invocations:
在以下情况下,扩展方法才适用:
An extension method is eligible if:
- 如上所示,Mj作为静态方法应用于参数时,可以访问并适用
- 从expr到Mj的第一个参数的类型之间存在隐式标识,引用或拳击转换.
...
如果在任何封闭的名称空间声明或编译单元中未找到候选集,则会发生编译时错误.
If no candidate set is found in any enclosing namespace declaration or compilation unit, a compile-time error occurs.
因此,您必须将DateTime
强制转换为Nullable<DateTime>
,或者从一开始就使用可空值:
So you have to cast the DateTime
to Nullable<DateTime>
explicitly or use a nullable from the beginning:
DateTime now = DateTime.Now;
((DateTime?)now).Test();
或
DateTime? now = DateTime.Now;
now.Test();
这篇关于具有可空值类型参数的扩展方法解析的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!