Return 使用类型动态枚举 null

Return Enum of null dynamically using the Type

在序列化程序中我有

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var enumText = reader.Value.ToString();
        var enumType = Nullable.GetUnderlyingType(objectType) ?? objectType;
        var defaultValue = GetDefault(objectType);
        //TODO: If empty or invalid, return null
        if (enumText == string.Empty)
        {
            return defaultValue;
        }

        ...
    }

objectType 是 System.Nullable``1[[SomeEnum]] 其中 SomeEnum 是普通枚举

对于 return 值 nullSystem.Nullable[SomeEnum] 的实例,GetDefault 应该是什么?

我试过了 Activator.CreateInstance(objectType); 其中 return 是 null 而不是 (SomeEnum?)null

我也试过了

    public object GetDefault(Type t)
    {
        return GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);
    }

    public T GetDefaultGeneric<T>()
    {
        return default(T);
    }

其中 return 为 null

是否可以 return (SomeEnum?)null 但来自 Type 对象?

我用这样的单元测试来测试它:

        var converter = new CustomStringEnumConverter();

        var result = converter.ReadJson(_readerMock.Object, nullableEnumType, "bad value", new JsonSerializer());
        result.Should().BeOfType(GetUnderlyingType(nullableEnumType));
        result.Should().Be(GetValue(nullableEnumType, null));

如果 return (SomeEnum?) null 则测试通过,但如果结果为 null

则测试失败

ReadJson 方法返回 null 应该是您需要做的全部。 Nullable<T> 是一种值类型(即使您可以测试并分配 null 给它)。当它被装箱到一个引用类型中时(例如 object),它会做以下两件事之一:

  1. 如果 Nullable<T> 表示的值不是 null,那么 Value 就像任何其他值类型一样被装箱。
  2. 如果 Nullable<T> 表示 null 值,则结果实际上是 null

拆箱时会发生相反的情况(从引用类型变为 Nullable<T>);如果引用类型是 null,那么会创建一个新的 Nullable<T> 实例,并设置它没有值,但是如果引用类型确实有值,那么一个新的 Nullable<T> 实例被创建并且引用类型中的值被设置为 Nullable<T>.

的当前值

调用 GetValueOrDefault 不起作用的原因是,对于 Nullable<T>,该方法的 return 类型是 T,它必须是值类型,所以它不能是 null.