如何解决更改属性值
我有一个要搜索的列表,然后我想将 DateTime 类型的变量更改为本地时间。
public static T LocalTime<T>(T value,string locationTimeZone)
{
if(value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IList collection = (IList)value;
foreach (var element in collection)
{
PropertyInfo[] props = element.GetType().GetProperties();
foreach (var property in props)
{
if (property.PropertyType == typeof(System.DateTime?))
{
var localTime = LocalTimeConvert("Alaskan Standard Time",DateTime.Now);
property.SetValue(property,localTime);
}
else if (property.PropertyType == typeof(System.DateTime))
{
property.SetValue(property,((System.DateTime)property.GetValue(property,null)).AddDays(10),null);
}
}
}
}
return value;
}
我正在为想要更改该值的部分而苦苦挣扎。如何从 PropertyInfo 获取值和更改值?
解决方法
替换此代码:
您应该将对象的实例传递给 getValue() 或 setValue() 而不是属性
public static T LocalTime<T>(T value,string locationTimeZone)
{
if (value.GetType().IsGenericType && value.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
IList collection = (IList)value;
foreach (var element in collection)
{
PropertyInfo[] props = element.GetType().GetProperties();
foreach (var property in props)
{
if (property.PropertyType == typeof(System.DateTime?))
{
var localTime = LocalTimeConvert("Alaskan Standard Time",DateTime.Now);
property.SetValue(element,localTime);
}
else if (property.PropertyType == typeof(System.DateTime))
{
property.SetValue(element,((System.DateTime)property.GetValue(element,null)).AddDays(10),null);
}
}
}
}
return value;
}
,
问题是当您应该传递要更改的对象时却传递了属性
property.SetValue(property,((System.DateTime)property.GetValue(property,null);
我认为您也可以像其他人所说的那样改进对泛型的使用
类似的东西
public static IList<T> LocalTime<T>(IList<T> value,string locationTimeZone)
{
foreach (var element in collection)
{
PropertyInfo[] props = element.GetType().GetProperties();
foreach (var property in props)
{
if (property.PropertyType == typeof(System.DateTime?))
{
var localTime = LocalTimeConvert("Alaskan Standard Time",DateTime.Now);
property.SetValue(property,localTime);
}
else if (property.PropertyType == typeof(System.DateTime))
{
property.SetValue(property,null);
}
}
}
return value;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。