简体   繁体   中英

Set property value of nullable datetime

Try to update a specific property of my model with Reflection. This works for all other types of my model except properties of type DateTime?

Code:

public void UpdateProperty(Guid topicGuid, string property, string value)
{
    var topic = Read(topicGuid);
    PropertyInfo propertyInfo = topic.GetType().GetProperty(property);
    propertyInfo.SetValue(topic, Convert.ChangeType(value, propertyInfo.PropertyType), null);

    topic.DateModified = DateTime.Now;

    Save();
}

The following error is thrown on the Convert.ChangeType part:

Invalid cast from 'System.String' to 'System.Nullable`1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'

How can this be solved?

Update

Got it working with Daniel A. White 's solution

Code updated (probably needs some finetuning, but it works):

public void UpdateProperty(Guid topicGuid, string property, string value)
{
    var topic = Read(topicGuid);

    PropertyInfo propertyInfo = topic.GetType().GetProperty(property);

    object changedType = propertyInfo.PropertyType == typeof(DateTime) || propertyInfo.PropertyType == typeof(DateTime?)
            ? DateTime.Parse(value)
            : Convert.ChangeType(value, propertyInfo.PropertyType);

    propertyInfo.SetValue(topic, changedType, null);

    topic.DateModified = DateTime.Now;

    Save();
}

Try to replace

Convert.ChangeType(value, propertyInfo.PropertyType)

by

Convert.ChangeType(value, Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType)

(Not tested)

尝试将值转换为DateTime:DateTime.Parse(value);

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