Why Nullable<​DateTime> can be assigned to a paramter which only can be implict converted from DateTime?

[亡魂溺海] 提交于 2019-12-11 11:06:08

问题


There is no implicit conversion from Nullable<​DateTime> to DynamoDB​Entry. But I have code like this. It works well.

class DocumentData {
    private readonly Document doc;

    protected void SetValue(string key, DateTime? dateTime)
    {
        DateTime? old = GetDateTime(key);
        if (old != dateTime)
            doc[key] = dateTime;
    }
}

In fact, I tested some other code. I think it's nothing to do with DynamoDB.

class TestDateTIme
{           
    public static void Test() { 
        DateTime? a = DateTime.UtcNow;
        Convert(a);
    }
    public static void Convert(MyClass m){
        return;
    }
}

class MyClass 
{
    public static implicit operator MyClass(DateTime date)
    {
         return new MyClass ();
    }
}

回答1:


Good question. What you dexcribe is this:

class MyClass 
{
    public static implicit operator MyClass(DateTime date)
    {
         return new MyClass ();
    }
}

That's an implicit user-defined conversion from a non-nullable value type (here DateTime) to the class type, a reference type.

Then a conversion DateTimeMyClass "induces" a conversion DateTime?MyClass as it seems.

With the above example, this compiles:

DateTime? nullableDateTime = XXX;
MyClass myClass = nullableDateTime;  // implicit conversion from nullable!

I tried to read carefully the part of the C# Language Specification beginning with:

User-defined implicit conversions

A user-defined implicit conversion from type S to type T is processed as follows: [...]

Here the source S is DateTime?, and the target T is MyClass. With the notation of the spec, S0 and Sx become DateTime and the conversion you wrote is "selected".

When nullableDateTime has a value, it is pretty clear that this value is unwrapped, then fed to the user-definede conversion of yours. It seems to be in agreement with the spec.

When nullableDateTime does not have a value (is null), it looks like the resulting myClass becomes a null of that type, that is a null reference of the class type. This is based on experimenting. I am not sure where in the spec this behavior, with null from struct to class, is described.

Conclusion: The behavior you asked about, is probably a consequence of the way the specification is written, but I am not sure where it says that null shall go to null without actually invoking your conversion method.



来源:https://stackoverflow.com/questions/18350297/why-nullabledatetime-can-be-assigned-to-a-paramter-which-only-can-be-implict

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!