我编写了一个程序,可以处理删除和更新,存储和搜索等文件。所有客户但我在类srialize中遇到了Deserialize方法的问题。
我一直收到以下错误:
“System.String”类型的对象无法转换为“System.Int32”类型
public T Deserialize<T>(string entity)
{
var obj = Activator.CreateInstance<T>();
var stringProps = entity.Split(',');
var objProps = obj.GetType().GetProperties();
var propIndex = 0;
for (int i = 0; i < stringProps.Length; i++)
{
if (objProps[propIndex].PropertyType.FullName == "System.String")
{
objProps[propIndex].SetValue(obj, stringProps[i], null);
}
else if (objProps[propIndex].PropertyType.FullName == "System.Int32")
{
objProps[propIndex].SetValue(obj, stringProps[i], null);
}
else if (objProps[propIndex].PropertyType.FullName == "System.DateTime")
{
var cultureInfo = new CultureInfo("fa-IR");
DateTime dateTime = Convert.ToDateTime(stringProps[i], cultureInfo);
objProps[propIndex].SetValue(obj, stringProps[i], null);
}
else
{
i--;
}
propIndex++;
}
return obj;
}
答案 0 :(得分:1)
您仍需要在通过反射设置数据时转换数据类型,修改代码以包含转换,如下所示
public T Deserialize<T>(string entity)
{
var obj = Activator.CreateInstance<T>();
var stringProps = entity.Split(',');
var objProps = obj.GetType().GetProperties();
var propIndex = 0;
for (int i = 0; i < stringProps.Length; i++)
{
if (objProps[propIndex].PropertyType.FullName == "System.String")
{
objProps[propIndex].SetValue(obj, stringProps[i], null);
}
else if (objProps[propIndex].PropertyType.FullName == "System.Int32")
{
objProps[propIndex].SetValue(obj, Convert.ToInt32(stringProps[i]), null);
}
else if (objProps[propIndex].PropertyType.FullName == "System.DateTime")
{
var cultureInfo = new CultureInfo("fa-IR");
DateTime dateTime = Convert.ToDateTime(stringProps[i], cultureInfo);
objProps[propIndex].SetValue(obj, stringProps[i], null);
}
else
{
i--;
}
propIndex++;
}
return obj;
}