简体   繁体   English

设置可空日期时间的属性值

[英]Set property value of nullable datetime

Try to update a specific property of my model with Reflection. 尝试使用Reflection更新模型的特定属性。 This works for all other types of my model except properties of type DateTime? 这适用于我的模型的所有其他类型,除了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: Convert.ChangeType部分抛出以下错误:

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 得到了Daniel A. White的解决方案

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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