zoukankan      html  css  js  c++  java
  • C#反射学习

    这天都在学习c#的反射原理,网上的资料很多。以前听说反射也仅仅是在《大话设计模式》里面直到一点点,了解不深。

    开始我还不知道反射到底有什么好处,后来我才知道利用反射我们可以在运行时的时候通过变量来实例化类的实例。可以有效避免了很多的逻辑判断。

    以下是我的测试的代码:

     

    using System;

    using System.Collections.Generic;

    using System.Text;

    using System.Reflection;    //反射需要引用的命名空间

     

    namespace 反射原理

    {

        class Program

        {       

            static void Main(string[] args)

            {

                string str = Console.ReadLine();

                Icon i = ConFactory.ReturnCon(str);

                i.OutputStr();

                Console.ReadKey();

            }

        }

        class ConFactory

        {

            private static readonly string AssemblyName = "反射原理";    //程序及

            public static Icon ReturnCon(string str)   //str参数是指类名

            {

                string ClassName = AssemblyName + "." + str;

                return (Icon)Assembly.Load(AssemblyName).CreateInstance(ClassName);   //生成特定类的实例,然后转换为接口返回

            }

        }

        interface Icon

        {

            void OutputStr();

        }

        class PersonCon : Icon

        {

            public void OutputStr()

            {

                Console.WriteLine("PersonCon");

            }

        }

        class WorldCon : Icon

        {

            public void OutputStr()

            {

                Console.WriteLine("WorldCon");

            }

        }

    }

     

    这样我们可以通过读取外部的配置文件来对我们的变量进行赋值,然后通过它来实例化特指的类。这招在多数据库的应用特别有效。我们只需要修改配置文件就可以达到更换数据库的目的。有效降低了类之间的耦合,更灵活,更容易修改

  • 相关阅读:
    机器学习入门-文本数据-使用聚类增加文本的标签属性
    机器学习入门-文本特征-使用LDA主题模型构造标签 1.LatentDirichletAllocation(LDA用于构建主题模型) 2.LDA.components(输出各个词向量的权重值)
    机器学习入门-文本特征-word2vec词向量模型 1.word2vec(进行word2vec映射编码)2.model.wv['sky']输出这个词的向量映射 3.model.wv.index2vec(输出经过映射的词名称)
    机器学习入门-数值特征-对数据进行log变化
    python中datetime.strptime(),strftime()的应用
    css中的','、'>'、'+'、'~'
    js中const,var,let区别
    css的#和.的区别
    js实现拖放
    [Usaco2005]Part Acquisition
  • 原文地址:https://www.cnblogs.com/saper/p/1421106.html
Copyright © 2011-2022 走看看