转换为通用可为空值

问题描述 投票:0回答:1

我制作了一个小的超时结构,并想添加转换以使其更易于使用:

public struct TimeoutValue<T>
{
    public static TimeSpan DefaultTimeout { get; } = TimeSpan.FromSeconds(5);

    public DateTime CreationTime { get; set; } = DateTime.UtcNow;
    public TimeSpan? CustomTimeout { get; set; } = null;

    public T Value { get; set; }

    public readonly bool IsTimeouted => DateTime.UtcNow - CreationTime >= (CustomTimeout ?? DefaultTimeout);

    public TimeoutValue(T value) => Value = value;
    public TimeoutValue(DateTime creationTime, T value) : this(value) => CreationTime = creationTime;
    public TimeoutValue(TimeSpan customTimeout, T value) : this(value) => CustomTimeout = customTimeout;
    public TimeoutValue(DateTime creationTime, TimeSpan customTimeout, T value) : this(creationTime, value) => CustomTimeout = customTimeout;

    public static explicit operator T(TimeoutValue<T> value) => value.Value;
    public static implicit operator TimeoutValue<T>(T value) => new(value);
    public static implicit operator T?(TimeoutValue<T> value) => value.IsTimeouted ? null : value.Value;
}

但是,最后一个不行。

现在的情况,由于显式运算符,它说它是双精度的,并且不接受返回 null。它似乎没有意识到它应该可以为空。

但是如果我做到了

Nullable<T>
,我只能将结构放入其中,这违背了我的结构的目的。我也无法返回值。那么值。

有人知道我如何才能完成这项工作吗?

c# nullable
1个回答
1
投票

where T : class
添加到您的结构中可以接受吗? 如果是这种情况,您可以只保留两个隐式运算符

public static implicit operator TimeoutValue<T>(T value) => new(value);
public static implicit operator T?(TimeoutValue<T> value) => value.IsTimeouted ? null : value.Value;
© www.soinside.com 2019 - 2024. All rights reserved.