jeudi 19 février 2015

c# DateTime returns default value when set up with reflection

I have a static method inside a class that sets up an object at runtime like described here: http://ift.tt/1AMjsW4


To that newly created object I add properties combined from different objects that are being sent to my method and I set the values in reflection and return the newly created object. All values appear to have values (so far I tested string and int) - but the values are there.


The problem is when I set a DateTime value to a DateTime property - the returned value is 01/01/0001 and not the date I have set.


Here is the code that sets the values in reflection:



foreach (string key in values.Keys)
{
if (sqlParams == null || sqlParams.Contains(key))
{
PropertyValue propertyValue = values[key];
object val = propertyValue.Value;
if (val == null)
val = getDefaultValue(propertyValue.PropertyType);
else if (propertyValue.PropertyType == typeof(DateTime) && (DateTime)propertyValue.Value == DateTime.MinValue)
val = new DateTime(1982, 5, 6);// (DateTime)System.Data.SqlTypes.SqlDateTime.MinValue;
myType.GetProperty(key).SetValue(obj, val);
}
}


Why aren't DateTime values being returned correctly?






Aucun commentaire:

Enregistrer un commentaire