gpt4 book ai didi

c# - 如何确定非空对象是否为可空结构?

转载 作者:太空狗 更新时间:2023-10-29 23:26:18 25 4
gpt4 key购买 nike

有什么方法可以知道吗?

我在 How to check if an object is nullable? 找到了一个帖子,问了一个非常相似的问题答案解释了如何确定对象是否可为空如果可以访问通用类型参数。这是通过使用 Nullabe.GetUnderlyingType(typeof(T)) 完成的。但是,如果您只有一个对象并且它不是 null,您能否确定它是否实际上是一个 Nullable ValueType?

换句话说,是否有比单独检查每个可能的可空值类型来确定装箱结构是否为值类型更好的方法?

void Main(){
Console.WriteLine(Code.IsNullableStruct(Code.BoxedNullable));
}


public static class Code{
private static readonly int? _nullableInteger = 43;

public static bool IsNullableStruct(object obj){
if(obj == null) throw new ArgumentNullException("obj");
if(!obj.GetType().IsValueType) return false;
return IsNullablePrimitive(obj);
}
public static bool IsNullablePrimitive(object obj){
return obj is byte? || obj is sbyte? || obj is short? || obj is ushort? || obj is int? || obj is uint? || obj is long? || obj is ulong? || obj is float? || obj is double? || obj is char? || obj is decimal? || obj is bool? || obj is DateTime? || obj is TimeSpan?;
}

public static object BoxedNullable{
get{ return _nullableInteger; }
}
}

-

更新

我找到了 this article at MSDN ,它表示您无法通过调用 GetType() 来确定类型是否为 Nullable 结构。

-

更新 #2

显然我建议的方法也不起作用,因为 int x = 4; Console.WriteLine(x is int?); 为真。 (见评论)

最佳答案

在您链接的问题中引用 Jon Skeet 的评论:

there's no such thing as a boxed nullable type - Nullable gets boxed to a null reference or a boxed int

因此在您的示例程序中,当 BoxedNullable 被传递给 IsNullableStruct 时,它接受一个 object 作为参数,该值已经是一个盒装 43,不再是可为 null 的任何内容。具有讽刺意味的是,x is int? 对于任何 int 都为 true,可以为 null 或其他,所以这只会增加困惑。

无论如何,根据 Jon 的评论,您最初的问题似乎没有意义。

关于c# - 如何确定非空对象是否为可空结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5972845/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com