C# 使用序列化+反射加载xml文档到类实例对象

添加引用

using System.Threading;
using System.Xml.Serialization;
using System.IO;
using System.Reflection;

 

#region 通过反序列化和反射将xml配置文档加载到类实例的公共属性   反射测试类 + 单例模式
    public class SystemConfig
    {
        private static readonly string defaultFileName = "Test.xml";
        private string _ip;
        private string _port;
        private static readonly object _lockobj = new object();
        private static SystemConfig _instance;

        public string Ip
        {
            get => _ip;
            set => _ip = value;
        }

        public string Port
        {
            get => _port;
            set => _port = value;
        }

        private SystemConfig()
        {

        }

        public static SystemConfig Instance
        {
            get
            {
                lock(_lockobj)
                {
                    if (_instance==null)
                    {
                        _instance = new SystemConfig();
                        _instance.LoadConfig(defaultFileName);
                    }
                }
                return _instance;
            }
        }

        public void LoadConfig(string xmlFile)
        {
            try
            {
                //获取xml路径
                string path;
                path = AppDomain.CurrentDomain.BaseDirectory;
                path = path.Replace("netcoreapp2.1", "Config");
                path = Path.Combine(path, xmlFile);

                if (!File.Exists(path))
                {
                    Console.WriteLine("XmlFile not found !");
                    return;
                }

                //反序列化
                XmlSerializer xmlSerializer = new XmlSerializer(typeof(SystemConfig));
                SystemConfig systemConfig;
                using (FileStream fileStream = new FileStream(path, FileMode.Open))
                {
                    systemConfig = (SystemConfig)xmlSerializer.Deserialize(fileStream);
                }

                //获取实例公共属性
                PropertyInfo[] propertyInfos = SystemConfig.Instance.GetType().GetProperties();

                //设置Value
                for (int i = 0; i < propertyInfos.Length; i++)
                {
                    if (propertyInfos[i].CanWrite)
                    {
                        propertyInfos[i].SetValue(this, propertyInfos[i].GetValue(systemConfig));
                    }
                }

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        
        /// <summary>
        /// 保存SystemConfig 实例对象到xml配置文件
        /// </summary>
        public void Save()
        {
            try
            {
                //获取xml路径
                string path;
                path = AppDomain.CurrentDomain.BaseDirectory;
                path = path.Replace("netcoreapp2.1", "Config");
                path = Path.Combine(path, defaultFileName);

                using (FileStream fileStream = new FileStream(path, FileMode.Truncate))
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(typeof(SystemConfig));
                    xmlSerializer.Serialize(fileStream, this);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            
        }

    }

    #endregion
        static void Main(string[] args)
         {
            //Mutex跨多个线程同步访问的类。只有一个线程能获得互斥锁定,访问受互斥保护的同步代码区域。
            //在Mutex类的构造函数中,可以指定互斥是否最初应由主调线程拥有,定义互斥的名称,获得互斥是否已存在的信息。
            bool flag = false;
            Mutex mutex = new Mutex(true, "Main", out flag);
            //第一个参数:true--给调用线程赋予互斥体的初始所属权
            //第一个参数:互斥体的名称
            //第三个参数:返回值,如果调用线程已被授予互斥体的初始所属权,则返回true
            if (!flag)
            {
                Console.WriteLine("程序已运行!");
                Console.ReadKey();
            }


            //测试属性配置
            SystemConfig systemConfig = SystemConfig.Instance;
            Console.WriteLine($"IP:{systemConfig.Ip}");
            Console.WriteLine($"Port:{systemConfig.Port}");
            
            systemConfig.Ip="128.0.0.1";
            systemConfig.Save();
            Console.WriteLine($"修改后 IP:{systemConfig.Ip}");
            Console.ReadKey();
        }

运行结果:

反射相关


            Assembly assembly= Assembly.Load("CsharpSenior"); //通过程序集名称加载程序集
            Assembly assembly_2 = Assembly.LoadFrom("CsharpSenior.dll"); //通过DLL文件名称返回Assembly对象
            Type type= assembly.GetType("CsharpSenior.Reflection.ReflectionTest"); //通过Assembly获取程序集中的类,参数必须是类的全名
            object instance= Activator.CreateInstance(type,new object[] {10 }); //用Activator的CreateInstance静态方法,生成新对象
            ConstructorInfo[] constructorInfos = type.GetConstructors(); //获取类的所有构造函数
            PropertyInfo[] propertyInfos= type.GetProperties(); //查看类中的属性
            propertyInfos[0].SetValue(instance,"xiaom");  //给属性赋值
            FieldInfo[] fieldInfos = type.GetFields();   //查看类中的public字段
            fieldInfos[0].SetValue(instance,20);  //给字段赋值
            MethodInfo methodInfo= type.GetMethod("Call"); //获取类中的具体方法
            object[] para = new object[] { 1,"2"};
            methodInfo.Invoke(instance, para);  //方法调用

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值