简体   繁体   English

创建一个具有不同底层类型的Nullable对象数组?

[英]Create an array of Nullable objects with different underlying type?

I have a number of nullable objects of different types (eg DateTime? , Guid? ) that I want to check for a value. 我有许多不同类型的可空对象(例如DateTime?Guid? ),我想检查一个值。

I'd like to avoid code like this: 我想避免这样的代码:

return SomeGuid.HasValue || SomeBool.HasValue || SomeDateTime.HasValue

but it does not seem possible to create an array of Nullable<object> . 但似乎不可能创建一个Nullable<object>数组。 I was hoping to do something like: 我希望做的事情如下:

return new Nullable<object>[] { SomeGuid, SomeBool, SomeDateTime }.Any(o => o.HasValue);

object is nullable per definition. object根据定义可以为空。

So the following works: 以下是有效的:

Guid? guid = null;
bool? boolean = null;
DateTime? date = DateTime.Now;

var test = new object[] { guid, boolean, date }.Any(o => o != null);

Do note Nullable<T> requires T to be a struct , ie a value type (not a reference type). 请注意Nullable<T>要求Tstruct ,即类型(不是引用类型)。 object is a reference type. object引用类型。

A little complicated, but you can wrap the nullable objects using a uniform interface, as follows: 有点复杂,但您可以使用统一的接口包装可空对象,如下所示:

interface INullableWrapper
{
    bool HasValue { get; }
    object Value { get; } // Careful: boxing!
}

class NullableWrapper<T> : INullableWrapper
    where T : struct
{
    public T? Nullable { get; private set; }

    public bool HasValue { get { return this.Nullable.HasValue; } }

    object INullableWrapper.Value { get { return this.Nullable.Value; } }

    public T Value { get { return this.Nullable.Value; } }

    public NullableWrapper(T? nullable)
    {
        this.Nullable = nullable;
    }
}

return new INullableWrapper[] { new NullableWrapper<int>(5), new NullableWrapper<string>("Hello") };

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

相关问题 C#将作为通用对象返回的数组转换为不同的基础类型 - C# converting an array returned as a generic object to a different underlying type 动态创建可为空的类型 - Create a nullable type dynamically 创建不同类型对象的列表 - create a List of different Type of Objects 使用FluentAssertions比较可空类型与其基础类型时,这是一个错误吗? - Is this a bug when comparing a nullable type with its underlying type using FluentAssertions? 装箱的可为空的基础类型可以强制转换为枚举,但装箱的枚举类型不能强制转换为可空类型 - Boxed nullable underlying type can be cast to enum but boxed enum type can't be cast to nullable type 底层对象空数组的类型 - Underlying object Type of an empty Array 将对象数组复制到不同类型的数组 - Copy array of objects to array of different type 是否有可能创建一个Foo的集合 <T> T被限制为非可空类型的对象? - Is it somehow possible to create a collection of Foo<T> objects where T is restricted to a non-nullable type? 将数组从可空类型转换为相同类型的不可空类型? - Convert array from nullable type to non-nullable of same type? 如何创建 class 类型对象的数组? - How to create an array of class type objects?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM