[英]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>
要求T
为struct
,即值类型(不是引用类型)。 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.