如何获取可为空原始类型数组的类型?

huangapple go评论78阅读模式
英文:

How to get the Type of an Array of Nullable Primitive?

问题

我有一个定义如下的属性:

public bool[] _array { get; set; }
public bool?[] _null_array { get; set; }

我按照 https://stackoverflow.com/questions/11347053/how-do-i-determine-the-underlying-type-of-an-array 中的说明进行了操作:

foreach (var _property in typeof(T).GetProperties())
{
    var _propertyType = _property.PropertyType;
    var _propertyName = _property.Name;

    var CheckArray = _propertyType.IsArray;
    var UType = _propertyType.GetElementType().Name;
    // 其他代码...
}

UType 的结果如下:

_array      => "Boolean"
_null_array => "Nullable`1"

如何获取可空原始类型的数组的类型?

谢谢。

英文:

I have a property defined as:

public bool[] _array { get; set; }                  
public bool?[] _null_array { get; set; }            

I followed the instructions in https://stackoverflow.com/questions/11347053/how-do-i-determine-the-underlying-type-of-an-array

foreach (var _property in typeof(T).GetProperties())
{ 
    var _propertyType = _property.PropertyType;
    var _propertyName = _property.Name;

    var CheckArray = _propertyType.IsArray;
    var UType      = _propertyType.GetElementType().Name;
    ....
}

The results for UType is:

_array      => "Boolean"
_null_array => "Nullable`1"

How do I get the type of an array of nullable primitive ?

Thanks.

答案1

得分: 1

你已经有了它。数组元素类型是 bool?,又称为 Nullable<bool>,也叫做 Nullable``1(只有一个反引号,怪罪于 Markdown),其泛型参数为 bool。如果你想要 bool,那么你需要在元素类型上使用 Nullable.GetUnderlyingType;这将对不是 Nullable<T> 的内容返回 null,所以考虑:

var type = _propertyType.GetElementType();
type = Nullable.GetUnderlyingType(type) ?? type;
var UType = type.Name;
英文:

You already have it. The array element type is bool? aka Nullable&lt;bool&gt; aka Nullable``1 (only one backtick, blame markdown) with generic argument bool. If you're after bool, then you'll want Nullable.GetUnderlyingType on the element type; this returns null for things that aren't Nullable&lt;T&gt;, so consider:

var type = _propertyType.GetElementType();
type = Nullable.GetUnderylingType(type) ?? type;
var UType = type.Name;

huangapple
  • 本文由 发表于 2023年1月9日 14:24:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053789.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定