有个对象,这个对象的所有属性通过XML序列化的方式(我是手动序列化的,也就是一个个属性转化为字符串写成配置文件)保存成XML文件,现在我想把这个对象还原,除了属性为String的能还原,其他的都会报错(数据类型不对)。
我贴下我的部分代码ChannelData cd = Activator.CreateInstance(typeChannel) as ChannelData;
            if (cd == null) return null;
            string className = Activator.CreateInstance(typeChannel).GetType().Name;
            XElement dataElement = cfgDataElement.Element(className);
foreach (PropertyInfo p in Activator.CreateInstance(typeChannel).GetType().GetProperties())
            {
                string pName = p.Name;
                string pValue = dataElement.Element(pName).Value;
                typeChannel.GetProperty(pName).SetValue(cd, pValue, null);
            }错误的地方
typeChannel.GetProperty(pName).SetValue(cd, pValue, null);因为pValue的类型不一定是String。
对象的属性的类型都是系统自带的类型,通过反射我能得到这个属性的类型的字符串比如System.int32,但是不知道怎么将那个pValue 转化为对应的属性的类型。
请大家帮帮忙,我该怎么做?

解决方案 »

  1.   

    to liuh6
    不行,同样是类型转换错误
    比如本来是int,现在是object to int,转化错误
      

  2.   

    简单的可以用  foreach (PropertyInfo p in Activator.CreateInstance(typeChannel).GetType().GetProperties())
                {
                    string pName = p.Name;
                    string pValue = dataElement.Element(pName).Value;
                    typeChannel.GetProperty(pName).SetValue(cd, Convert.ChangeType(pValue, p.PropertyType), null);
                }
    复杂的自己转把