jeudi 10 septembre 2015

Simplify checking what type it is and format the string with reflection?

Is there a way for me to simplify the if(value is X) then customize the ToString()?

var value = FindBodyLine(iwant, props, obj);

if (value != null)
{
  if(value is DateTime)
   {    
    var date = value as DateTime? ?? new DateTime();
    sb.Append(date.ToString("MM/dd/yyyy")));
   }
   else if(value is float)
   {    
     var floatData = value as float?? new float();
     sb.Append(floatData.ToString(CultureInfo.CreateSpecificCulture("de-DE")));
   }
}



 private object FindBodyLine(string iwant, PropertyInfo[] props, object obj)
 {

   var itemFound = from x in props where x.Name == iwant select x;

   var value = itemFound.First().GetValue(obj, null);  
   return value;
 }

I thought about having a Dictionary

 typeOf(DateTime), "mm/DD/yyyy"
 typeOf(float), "de-De"

and have a looup but I can't convert value to the type.





Aucun commentaire:

Enregistrer un commentaire