gpt4 book ai didi

c# - Nullable 实现

转载 作者:行者123 更新时间:2023-11-30 20:24:53 25 4
gpt4 key购买 nike

我正在尝试实现 Nullable 类型。但是下面提到的代码不支持值类型数据类型的空值。

using System;
using System.Runtime;
using System.Runtime.InteropServices;

namespace Nullable
{

[Serializable, StructLayout(LayoutKind.Sequential)]
public struct Nullable<T> where T : struct
{
private bool hasValue;

public bool HasValue
{
get { return hasValue; }
}

internal T value;

public Nullable(T value)
{
this.value = value;
this.hasValue = true;
}

public T Value
{
get
{
if (!this.hasValue)
{
new InvalidOperationException("No value assigned");
}
return this.value;
}
}

public T GetValueOrDefault()
{
return this.value;
}

public T GetValueOrDefault(T defaultValue)
{
if (!this.HasValue)
{
return defaultValue;
}
return this.value;

}

public override bool Equals(object obj)
{
if (!this.HasValue)
{
return obj == null;
}
if (obj == null)
{
return false;
}
return this.value.Equals(obj);
}

public override int GetHashCode()
{
if (!this.hasValue)
{
return 0;
}
return this.value.GetHashCode();
}

public override string ToString()
{
if (!this.hasValue)
{
return string.Empty;
}
return this.value.ToString();
}

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

public static explicit operator T(Nullable<T> value)
{
return value.Value;
}
}
}

当我尝试将值分配为 null 时,它抛出错误“无法将 null 转换为‘Nullable.Nullable’,因为它是不可为 null 的值类型”

我需要做什么来解决这个问题?

最佳答案

正在分配 nullNullable<T>只是分配 new Nullable<T>() 的语法糖,它是 C# 语言的一部分,您不能将该功能添加到您的自定义类型。

C# 规范,

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.

关于c# - Nullable<T> 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25629207/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com