简体   繁体   中英

How to get type of Nullable data type?

I have field's data type defined in database. I want to convert field's value to its specific data type. The code below works for System.Int32

 var fieldValue = "1234";
 var fieldDataType = "System.Int32";
 var type = Type.GetType(fieldDataType);
 TypeConverter typeConverter = TypeDescriptor.GetConverter(type);
 var result = typeConverter.ConvertFromString(fieldValue);

However, It does not work when dataType is System.Nullable<System.Int32>

What is the valid value for Nullable Integer DataType? (I am going to use the same for other datatypes)

EDIT 1 ( More details)
In database i have fields defined along with their data types. I am rendering TextBox dynamically on UI for each field. When user submits the form , I am using custom model binding in ASP.NET Core to bind these fields to JObject. Something like below

var model = new MyModel()
   {
     CustomFields = new JObject()
   };

foreach(var key in form.Keys)
{
    var val = form[key];

    var fields = GetFieldsFromDB();
    var field = fileds.Where(x=>x.FieldName == key).Single();
    

     TypeConverter typeConverter = TypeDescriptor.GetConverter(Type.GetType(field.DataType);
       var result = typeConverter.ConvertFromString(fieldValue);

     model.CustomFields.Add(key,result);
    
  
}

I am trying to avoid switch statement or if else for each available.Net DataTypes

You need to use the internal type name:

var fieldDataType = "System.Nullable`1[System.Int32]";

This is also what's computed by:

var fieldDataType = "" + typeof(Nullable<int>);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM