Nullable implementation

前端 未结 3 466
暗喜
暗喜 2021-01-22 10:27

I am trying to implement Nullable type. But below mentioned code doesn\'t support null value for valuetype datatypes.

using System;
using System.Runtime;
using S         


        
相关标签:
3条回答
  • 2021-01-22 10:49

    Assigning null to Nullable<T> is just a syntactic sugar for assigning new Nullable<T>(), it's part of C# language, and you can't add that feature to you custom type.

    C# spec,

    4.1.10 Nullable types

    A nullable type can represent all values of its underlying type plus an additional null value. A nullable type is written T?, where T is the underlying type. This syntax is shorthand for System.Nullable, and the two forms can be used interchangeably.

    6.1.5 Null literal conversions

    An implicit conversion exists from the null literal to any nullable type. This conversion produces the null value (§4.1.10) of the given nullable type.

    0 讨论(0)
  • 2021-01-22 11:09

    You are declaring your homegrown Nullable as a struct, and a struct is not nullable. You should declare it as a class instead.

    this code should throw the same error you are having, switching the Point type declaration from struct to class should fix it.

    void Main()
    {
        Point p = null;
    }
    
    // Define other methods and classes here
    struct Point
    {
     public int X   {get; set;}
     public int Y   {get; set;}
    }
    
    0 讨论(0)
  • 2021-01-22 11:11

    You can't.
    Nullable<T> is a special case. It has special processing on CLR level (this isn't a pure C# language feature - in particular, CLR supports special scenarios for boxing/unboxing nullables).

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