C#-如何检测与可为空的属性结合的数据类型

问题描述 投票:0回答:1

我正在使用反射通过检测通用类对象的数据类型(例如System.String,System.DateTime等)并根据数据类型转换值,例如:]来检索通用类对象的属性

                switch (prop.PropertyType.FullName)
                {
                    case "System.String":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            string.Empty : Convert.ToString(_propertyDataValue));
                        break;
                    case "System.Int32":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            -1 : Convert.ToInt32(_propertyDataValue));
                        break;
                    case "System.DateTime":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            DateTime.MinValue : Convert.ToDateTime(_propertyDataValue));
                        break;
                    case "System.Double":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            0 : Convert.ToDouble(_propertyDataValue));
                        break;
                    case "System.Boolean":
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            false : Convert.ToBoolean(_propertyDataValue));
                        break;
                    default:
                        prop.SetValue(resultObject, _propertyDataValue == DBNull.Value ?
                            string.Empty : Convert.ToString(_propertyDataValue));
                        break;
                }

但是,当我遇到定义为int?的属性时,加倍?或DateTime?这将是一个Nullable类型,但我无法找出该属性的确切数据类型t 反射仅给我提供了类型为“ System.Nullable”]的信息,它是否可以检测组合数据类型在后面?

c# .net reflection nullable
1个回答
0
投票

正如@madreflection在评论部分所说。您需要使用Nullable.GetUnderlyingType,如下所示:

Nullable.GetUnderlyingType
© www.soinside.com 2019 - 2024. All rights reserved.