C# 4: Dynamic and Nullable<>

后端 未结 1 971
无人及你
无人及你 2020-12-24 11:47

So I\'ve got some code that passes around this anonymous object between methods:

var promo = new
{
    Text = promo.Value,
    StartDate = (startDate == null         


        
相关标签:
1条回答
  • 2020-12-24 12:26

    Great question. Two facts that you probably don't know:

    1. Dynamic behind the scenes is just object. That is, a "dynamic" variable is an "object" variable with a hint to the compiler that says "generate dynamic operations on this variable when it is used."

    2. There is no such thing as a boxed nullable. When you box an int? to object you get either a null object reference or a boxed int. The nullable wrapper around the int is thrown away.

    Now it should be clear what is going on here. If promo is dynamic then promo.StartDate is dynamic. Which means that at runtime, it is object. Which means that if it is of value type, it is boxed. Which means that if it was nullable, it is now either a null reference or a boxed non-nullable value. Either way, that thing doesn't have a HasValue property. If you want to know whether it was in its value type form a nullable value type set to null, then check whether promo.StartDate is null or not.

    0 讨论(0)
提交回复
热议问题