Пример #1
0
        public static T LoadModel <T>(string filename) where T : new()
        {
            T           val            = new T();
            Type        typeFromHandle = typeof(T);
            XmlDocument xmlDocument    = new XmlDocument();

            try
            {
                xmlDocument.Load(filename);
            }
            catch
            {
                return(default(T));
            }
            PropertyInfo[] properties = typeFromHandle.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            PropertyInfo[] array      = properties;
            foreach (PropertyInfo propertyInfo in array)
            {
                if (!(propertyInfo?.CanWrite ?? false))
                {
                    continue;
                }
                XmlNode xmlNode = xmlDocument.SelectSingleNode(typeFromHandle.Name + "/" + propertyInfo.Name);
                if (xmlNode != null)
                {
                    Type propertyType = propertyInfo.PropertyType;
                    if (propertyType == typeof(string))
                    {
                        propertyInfo.SetValue(val, xmlNode.InnerText, null);
                    }
                    else if (propertyType == typeof(int))
                    {
                        propertyInfo.SetValue(val, FPUtils.StrToInt(xmlNode.InnerText), null);
                    }
                    else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))
                    {
                        propertyInfo.SetValue(val, FPUtils.StrToDateTime(xmlNode.InnerText), null);
                    }
                    else if (propertyType == typeof(decimal))
                    {
                        propertyInfo.SetValue(val, FPUtils.StrToDecimal(xmlNode.InnerText), null);
                    }
                    else if (propertyType == typeof(float))
                    {
                        propertyInfo.SetValue(val, FPUtils.StrToFloat(xmlNode.InnerText), null);
                    }
                    else if (propertyType == typeof(double))
                    {
                        propertyInfo.SetValue(val, FPUtils.StrToDouble(xmlNode.InnerText), null);
                    }
                    else if (propertyType == typeof(bool))
                    {
                        propertyInfo.SetValue(val, FPUtils.StrToBool(xmlNode.InnerText, false), null);
                    }
                    else if (propertyType == typeof(short))
                    {
                        propertyInfo.SetValue(val, short.Parse(FPUtils.StrToInt(xmlNode.InnerText).ToString()), null);
                    }
                }
            }
            return(val);
        }