C# Nullable

判断对象是否为null否则报错

string? a = string.Empty;
if (a is null)
if (ReferenceEquals(a, null))
if (a == null)


public void GetUser(string name) => ArgumentNullException.ThrowIfNull(nameof(name));

var a= b??throw new ArgumentNullException("Name must not be null")

//语法糖(目前没有上线)
public void GetUser(string name!!) => Console.WriteLine(DBNull.Value);

DBNull

一般用于判断DB和DataTable的值是否为null

Console.WriteLine(DBNull.Value);
Console.WriteLine(null != DBNull.Value);

public void A (object? a)
{
    Console.WriteLine(a!=null);
    Console.WriteLine(a!=DBNull.Value);
}

检查元素是否可为空的反射API

提供来自反射成员的可空性信息和上下文:

  • ParameterInfo 参数
  • FieldInfo 字段
  • PropertyInfo 属性
  • EventInfo 事件
var example = new Example();
var nullabilityInfoContext = new NullabilityInfoContext();
foreach (var propertyInfo in example.GetType().GetProperties())
{
    var nullabilityInfo = nullabilityInfoContext.Create(propertyInfo);
    Console.WriteLine($"{propertyInfo.Name} property is {nullabilityInfo.WriteState}");
}

// Output:
// Name property is Nullable
// Value property is NotNull

class Example
{
    public string? Name { get; set; }
    public string Value { get; set; }
}

检查嵌套元素是否可为空的反射API

允许您获取嵌套元素的可为空的信息, 您可以指定数组属性必须为非空,但元素可以为空,反之亦然。

Type exampleType = typeof(Example);
PropertyInfo notNullableArrayPI = exampleType.GetProperty(nameof(Example.NotNullableArray));
PropertyInfo nullableArrayPI = exampleType.GetProperty(nameof(Example.NullableArray));

NullabilityInfoContext nullabilityInfoContext = new();

NullabilityInfo notNullableArrayNI = nullabilityInfoContext.Create(notNullableArrayPI);
Console.WriteLine(notNullableArrayNI.ReadState);              // NotNull
Console.WriteLine(notNullableArrayNI.ElementType.ReadState);  // Nullable

NullabilityInfo nullableArrayNI = nullabilityInfoContext.Create(nullableArrayPI);
Console.WriteLine(nullableArrayNI.ReadState);                // Nullable
Console.WriteLine(nullableArrayNI.ElementType.ReadState);    // Nullable

class Example
{
    public string?[] NotNullableArray { get; set; }
    public string?[]? NullableArray { get; set; }
}

API接口报错案例

项目中使用了<Nullable>enable</Nullable>
Api报错,但是字段没有标识[Required]

{
    "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
    "title": "One or more validation errors occurred.",
    "status": 400,
    "traceId": "00-8d8245e63ed44d0e0a45bd96350980ee-9f6a21dba718ebd8-00",
    "errors": {
        "Name": [
            "The Name field is required."
        ]
    }
}

需要全局添加以下配置

services.AddControllers(options => options.SuppressImplicitRequiredAttributeForNonNullableReferenceTypes = true);
posted @ 2023-03-20 17:02  雨水的命运  阅读(133)  评论(0编辑  收藏  举报