简体   繁体   English

如何在 Nullable 中使用运算符“is”

[英]How to use operator "is" with Nullable

I want to use the "is" operator to unwrap Nullable.我想使用“is”运算符来解开 Nullable。 Something like:就像是:

if(nullable is not null notNullValue)
    notNullValue.ToString();

The workaround I'm using:我正在使用的解决方法:

if(value is SomeType notNullValue)
    notNullValue.ToString();

Using an additional variable in this case is ugly:在这种情况下使用附加变量是丑陋的:

class Sample {
    public Enum? Get() {...}
}
data.Select(x => (Sample)x)
    .Where(x => x.Get() is Enum enumValue ? StrictCheck(enumValue) : false)
    .Select(...)
    .ToArray();

Is there no way not to re-write the type?有没有办法不重写类型?

Seems like the best solution:似乎是最好的解决方案:

    public static bool TryGetValue<T>(this T? nullable, out T value) where T : struct {
        if (nullable is T notNullValue) {
            value = notNullValue;
            return true;
        }
        value = default(T);
        return false;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM