在C#.NET可选回报可选、NET

2023-09-03 01:27:25 作者:一生寥寥好幸运遇见你

Java的1.8接收可选类,这使我们能够明确地说,当一个方法可能会返回一个空值和力的消费来验证,如果它不为空(是present ())使用它之前。

Java 1.8 is receiving the Optional class, that allows us to explicitly say when a method may return a null value and "force" its consumer to verify if it is not null (isPresent()) before using it.

我看到C#有可空,即有类似的功能,但基本类型。它似乎是用于的数据库查询,以区分当一个值存在,并且是从0时,它不存在,并且是空

I see C# has Nullable, that does something similar, but with basic types. It seems to be used for DB queries, to distinguish when a value exists and is 0 from when it doesn't exist and is null.

但似乎C#的可空不为对象的工作,只为基本类型,而Java的可选仅适用于对象而不是基本类型。

But it seems that C#'s Nullable doesn't work for objects, only for basic types, while Java's Optional only works for objects and not for basic types.

有没有在C#中的可空/可选类,这迫使我们以测试对象的提取和使用它之前存在?

Is there a Nullable/Optional class in C#, that forces us to test if object exists before extracting and using it?

推荐答案

不是在语言,没有,但你可以使自己的:

Not in the language, no, but you can make your own:

public struct Optional<T>
{
    public bool HasValue { get; private set; }
    private T value;
    public T Value
    {
        get
        {
            if (HasValue)
                return value;
            else
                throw new InvalidOperationException();
        }
    }

    public Optional(T value)
    {
        this.value = value;
        HasValue = true;
    }

    public static explicit operator T(Optional<T> optional)
    {
        return optional.Value;
    }
    public static implicit operator Optional<T>(T value)
    {
        return new Optional<T>(value);
    }

    public override bool Equals(object obj)
    {
        if (obj is Optional<T>)
            return this.Equals((Optional<T>)obj);
        else
            return false;
    }
    public bool Equals(Optional<T> other)
    {
        if (HasValue && other.HasValue)
            return object.Equals(value, other.value);
        else
            return HasValue == other.HasValue;
    }
}

请注意,您将无法效仿可空与其中的某些行为; T&GT; ,如框可为空值,没有值设置为null,而能力比盒装为空,因为它有特殊的编译器支持(和其他)的行为。

Note that you won't be able to emulate certain behaviors of Nullable<T>, such as the ability to box a nullable value with no value to null, rather than a boxed nullable, as it has special compiler support for that (and a some other) behavior.