Extension method resolution with nullable value type params

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

    var isn't a type. The actual type is figured out at compile-time. If you set DateTime.Now for a var, it will recognize as a DateTime type, not a Nullable, and that's why it doesn't compile.

    var variables are also known as Implicitly Typed Local Variables (C# Programming Guide)

    By the way, you can also create a generic extension method for nullable types:

    public static T? GenericMethod(this T? source) where T : struct
    {
        //Do something
    }
    

    and you can call whatever is nullable, declaring its type:

    DateTime? dateTimeNullable = DateTime.Now;
    dateTimeNullable.GenericMethod();
    
    int? intNullable = 0;
    intNullable.GenericMethod();
    

提交回复
热议问题