开发者

Reflection - set object property considering data type

I already found out that it is possible to set the value of a property using reflection: Set o开发者_Go百科bject property using reflection

But my problem is that my data exists only as string. Therefore of course I always get an exception because it is not the right type.

Is there a way of automatically trying to parse the string to the according type (DateTime, int, decimal, float)?

Below is the code I'm using:

Type myType = obj.GetType();
PropertyInfo[] props = myType.GetProperties();

foreach (PropertyInfo prop in props)
{
   setProperty(obj, prop, data[prop.Name]);
}

data is a simple associative array that contains the data as string. These data are supposed to be mapped into obj.


You can use the Convert class:

   var value = Convert.ChangeType(data[prop.Name], prop.PropertyType);
   setProperty(obj, prop, value);


You should be able to use the TypeConverter:

var converter = TypeDescriptor.GetConverter(prop.PropertyType);
var value = converter.ConvertFromString(data[prop.Name]);
setProperty(obj,prop,value);


You can use the TypeConverter class in System.ComponentModel:

foreach (PropertyInfo prop in props)
{
    var value = data[prop.Name];
    prop.SetValue(obj, TypeConverter.ConvertTo(value, prop.PropertyType), null);
}


  PropertyInfo[] Properties = typeof(InvoiceLineItemSummary).GetProperties();     

            foreach (PropertyInfo objProperty in Properties)
            {
                    if (columns.ConvertAll(column=>column.ToLower()).Contains(objProperty.Name.ToLower()))
                    {
                        if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
                        {
                            if (Nullable.GetUnderlyingType(objProperty.PropertyType).ToString() == "System.Decimal")
                                vm.InvoiceLineItemSummaries.ToList().ForEach(val => val.GetType().GetProperty(objProperty.Name).SetValue(val,  Math.Round(Convert.ToDecimal(val.GetType().GetProperty(objProperty.Name).GetValue(val, null)), 2), null));

                        }
                        else if(objProperty.PropertyType.ToString() == "System.Decimal")
                            vm.InvoiceLineItemSummaries.ToList().ForEach(val => val.GetType().GetProperty(objProperty.Name).SetValue(val, Math.Round(Convert.ToDecimal(val.GetType().GetProperty(objProperty.Name).GetValue(val, null)), 2), null));
                    }  
            }


//vm.InvoiceLineItemSummary is List of classobject
//InvoiceLineItemSummary is class
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜