2.4 C#开发环境 xml格式保存参数

时间:2024-07-06 20:28:28

2.4C#开发环境 xml格式保存参数

保存参数有很多种方法, 这里只以xml格式保存作为说明

1 参数Class 举例

说明: Mat类不能够序列化
目的:能够把CFilter_Param 的实例保存到本地,并且能够在切换程序时导入参数

/// <summary>
/// CFilter_Param
/// VisionTool param 举例说明
/// </summary>
public class CFilter_Param
{
    [XmlIgnore]
    public Mat m_register_img;
    public  BD_Vision.Region m_region;  //ROI--》Region 
    public  ROI_single[] m_rois;  //ROI 交互窗口
    public CFilter_Param()
    {
        m_register_img = new Mat();
        m_region = new BD_Vision.Region();
        m_rois =  ROI_single.init(5);
    }
}

2 读取本地参数 Read_XML_File_Deserializer

一般在切换程序时 ,更具程序号,读取所有参数

#region 反序列化  
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="xml">XML字符串</param>
/// <returns></returns>
public object Deserialize(Type type, string xml)
{
    try
    {
        using (StringReader sr = new StringReader(xml))
        {
            XmlSerializer xmldes = new XmlSerializer(type);
            object obj = xmldes.Deserialize(sr);
            if (obj == null)
            {
                int a = 0;
            }
            return obj;
        }
    }
    catch (Exception e)
    {
        return null;
    }
}
/// <summary>
/// 反序列化
/// </summary>
/// <param name="type"></param>
/// <param name="xml"></param>
/// <returns></returns>
public object Deserialize(Type type, Stream stream)
{
    XmlSerializer xmldes = new XmlSerializer(type);
    return xmldes.Deserialize(stream);
}
#endregion
/// <summary>
/// Read_XML_File_Deserializer
/// </summary>
/// <param name="filepath"></param>
/// <param name="filename"></param>
/// <param name="type"></param>
/// <returns></returns>
public object Read_XML_File_Deserializer(string filepath, string filename, Type type)
{
    XmlDocument xmlDoc = new XmlDocument();
    string xml;
    try
    {
        // 判断是否文件存在
        if (filepath + filename != "")
        {
            // 1 load fiel
            xmlDoc.Load(filepath + filename);
            xml = xmlDoc.InnerXml;
            xmlDoc.RemoveAll();
            xmlDoc = null;
            return Deserialize(type, xml);
        }
        else return null;
    }
    catch (Exception ex)
    {
        throw new Exception("ReadXMLSerialize:" + ex.Message);
    }
}

3 保存到本地 Save_XML_File_Serialize

一般在参数详细设定后,更新并且保存到本地

#region 序列化
/// <summary>
/// 序列化
/// </summary>
/// <param name="type">类型</param>
/// <param name="obj">对象</param>
/// <returns></returns>
public string Serializer(Type type, object obj)
{
   MemoryStream Stream = new MemoryStream();
   XmlSerializer xml = new XmlSerializer(type);
   try
   {
       //序列化对象
       xml.Serialize(Stream, obj);
   }
   catch (Exception ex)
   {
       throw new Exception("Serializer:" + ex.Message);
   }
   Stream.Position = 0;
   StreamReader sr = new StreamReader(Stream);
   string str = sr.ReadToEnd();

   sr.Dispose();
   Stream.Dispose();

   return str;
}

#endregion
/// <summary>
/// Save_XML_File_Serialize
/// </summary>
/// <param name="filepath"></param>
/// <param name="filename"></param>
/// <param name="type"></param>
/// <param name="obj"></param>
/// <returns></returns>
public bool Save_XML_File_Serialize(string filepath, string filename, Type type, object obj)
{
   bool b_status = true;
   XmlDocument xmlDoc = new XmlDocument();
   string xml;
   try
   {
       if (obj != null && filepath + filename != "")
       { //1创建文档

           xml = Serializer(type, obj);
           //  
           xmlDoc.LoadXml(xml);
           xmlDoc.Save(filepath + filename);
           // dispose
           xmlDoc.RemoveAll();
           xmlDoc = null;
       }
   }
   catch (Exception ex)
   {
       throw new Exception("SaveXMLSerialize:" + ex.Message);
   }
   return b_status;
}

4 class 参数的DeepCopy

场景: 参数设定时,为了避免直接修改原始参数,防止无炒作,一般会DeepCopy VisionParam ,当确定需要更新时,才会更新并且保存
说明: class 类型数据一般都是指针传递,例如Mat 或者List ,需要单独处理

 /// <summary>
/// 对象拷贝
/// 需要对Mat类型单独处理
/// </summary>
/// <param name="obj">被复制对象</param>
/// <returns>新对象</returns>
public static object DeepCopyOjbect(object obj)
{
    if (obj == null)
    {
        return null;
    }
    Object targetDeepCopyObj;
    Type targetType = obj.GetType();
    try
    {
        switch (targetType.Name)
        {
            default:
                //值类型  
                if (targetType.IsValueType == true)
                {
                    targetDeepCopyObj = obj;
                }
                //引用类型   
                else
                {
                    targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象   
                    System.Reflection.MemberInfo[] memberCollection = obj.GetType().GetMembers();
                    foreach (System.Reflection.MemberInfo member in memberCollection)
                    {
                        //拷贝字段
                        if (member.MemberType == System.Reflection.MemberTypes.Field)
                        {
                            System.Reflection.FieldInfo field = (System.Reflection.FieldInfo)member;
                            Object fieldValue = field.GetValue(obj);
                            if (fieldValue is ICloneable)
                            {
                                field.SetValue(targetDeepCopyObj, (fieldValue as ICloneable).Clone());
                            }
                            else
                            {
                                field.SetValue(targetDeepCopyObj, DeepCopyOjbect(fieldValue));
                            }

                        }//拷贝属性
                        else if (member.MemberType == System.Reflection.MemberTypes.Property)
                        {
                            System.Reflection.PropertyInfo myProperty = (System.Reflection.PropertyInfo)member;
                            MethodInfo info = myProperty.GetSetMethod(false);
                            if (info != null)
                            {
                                try
                                {
                                    object propertyValue = myProperty.GetValue(obj, null);
                                    if (propertyValue is ICloneable)
                                    {
                                        myProperty.SetValue(targetDeepCopyObj, (propertyValue as ICloneable).Clone(), null);                                    }
                                    else
                                    {
                                        myProperty.SetValue(targetDeepCopyObj, DeepCopyOjbect(propertyValue), null);
                                    }
                                }
                                catch (System.Exception ex)
                                {
                                    //  MessageBox.Show(myProperty.ToString());
                                    return null;
                                }
                            }
                        }
                    }
                }
                break;
            case "Mat":
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象
                targetDeepCopyObj = obj;
                break;
            case "List`1":
                targetDeepCopyObj = System.Activator.CreateInstance(targetType);   //创建引用对象    
                targetDeepCopyObj = obj;
                break;

        }
    }
    catch (Exception ex)
    {
        // MessageBox.Show(targetType.ToString());
        targetDeepCopyObj = null;
    }
    return targetDeepCopyObj;
}