gpt4 book ai didi

c# - 设置可为 null 的日期时间的属性值

转载 作者:太空狗 更新时间:2023-10-29 22:22:20 25 4
gpt4 key购买 nike

尝试使用反射更新模型的特定属性。这适用于除 DateTime 类型的属性之外的所有其他类型的模型吗?

代码:

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

Convert.ChangeType 部分抛出以下错误:

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

如何解决?

更新

得到它与 Daniel A. White 的解决方案一起工作

代码已更新(可能需要一些微调,但它有效):

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

最佳答案

尝试替换

Convert.ChangeType(value, propertyInfo.PropertyType)

通过

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

(未测试)

关于c# - 设置可为 null 的日期时间的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27744330/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com