Extension method resolution with nullable value type params

后端 未结 5 1866
没有蜡笔的小新
没有蜡笔的小新 2021-01-19 05:54
public static class Extension
{
    public static void Test(this DateTime? dt)
    {
    }
}


void Main()
{
    var now = DateTime.Now;
    Extension.Test(now); //          


        
5条回答
  •  臣服心动
    2021-01-19 06:46

    A DateTime is not convertible to Nullable explicitly.

    The C# specification, 7.6.5.2 Extension method invocations:

    An extension method is eligible if:

    • Mj is accessible and applicable when applied to the arguments as a static method as shown above
    • An implicit identity, reference or boxing conversion exists from expr to the type of the first parameter of Mj.

    ...

    If no candidate set is found in any enclosing namespace declaration or compilation unit, a compile-time error occurs.

    So you have to cast the DateTime to Nullable explicitly or use a nullable from the beginning:

    DateTime now = DateTime.Now;
    ((DateTime?)now).Test();
    

    or

    DateTime? now = DateTime.Now;
    now.Test();
    

提交回复
热议问题