csharp 表示永远不会赋值为null的引用类型。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 表示永远不会赋值为null的引用类型。相关的知识,希望对你有一定的参考价值。

public struct NotNull<T> where T : class
{
    private T mValue;
    public T Value
    {
        get { return this.mValue; }
        set
        {
            if( value == null )
                throw new ArgumentNullException( "value" );
            
            this.mValue = value;
        }
    }
    
    // Prior to C# 6.0, structs were not allowed to contain user-defined,
    // parameterless constructors. Remove the preprocessor directive
    // or define 'CSHARP6' in your preferred way to enable this constructor.
#if CSHARP6
    public NotNull()
    {
        throw new InvalidOperationException( "NotNull must be initialized with a value." );
    }
#endif

    public NotNull( T value )
    {
        Value = value;    
    }

    public static implicit operator T( NotNull<T> instance )
    {
        return instance.Value;
    }

    public static implicit operator NotNull<T>( T value )
    {
        return new NotNull<T>( value );
    }

    public override string ToString()
    {
        return this.Value.ToString();    
    }

    public static bool operator ==( NotNull<T> left, T right )
    {
        return right == null ? false : left.Equals( right );    
    }

    public static bool operator !=( NotNull<T> left, T right )
    {
        return !( left == right );  
    }

    public override bool Equals( object other )
    {
        if( other == null )
            return false;
        
        if( other is NotNull<T> )
            return this.Equals( (NotNull<T>)other );
        
        if( other is T )
            return this.Equals( (T)other );

        return false;
    }

    public bool Equals( NotNull<T> other )
    {
        return this.Value.Equals( other.Value );
    }

    public override int GetHashCode()
    {
        return this.Value.GetHashCode();    
    }
}

以上是关于csharp 表示永远不会赋值为null的引用类型。的主要内容,如果未能解决你的问题,请参考以下文章

请问一下C#这句代码啥意思啊? decimal? a= 0; 看着像条件运算,又不像!

深入理解javascript之null和undefined

PHP之null

Kotlin初级- - - 空安全.md

Kotlin初级- - - 空安全.md

JVM 引用类型