Extension method resolution with nullable value type params

后端 未结 5 1868
没有蜡笔的小新
没有蜡笔的小新 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:56

    Because you wrote an extension for DateTime? and not for DateTime.

            DateTime? now = DateTime.Now;
            Extension.Test(now); // ok
            now.Test(); // no compile time error
    

    or

            var now = new DateTime?(DateTime.Now);
            Extension.Test(now); // ok
            now.Test(); // no compile time error
    

    will work.

提交回复
热议问题