英文:
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<bool>
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<T>
, so consider:
var type = _propertyType.GetElementType();
type = Nullable.GetUnderylingType(type) ?? type;
var UType = type.Name;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论