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");

            }

        }

    }

     

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

  • 相关阅读:
    Linux-05安装python3,jupyter(朱皮特)
    Linux-04Vim
    calloc()的使用
    根目录挂载位置错误记录
    arm裸机通过uboot运行hello world程序测试结果
    编译Uboot——错误记录
    将make的输出重定向到文件(转)
    Linux下JDK+Eclipse安装
    使用gdb+core查看错误信息
    Ubuntu下安装tftp
  • 原文地址:https://www.cnblogs.com/saper/p/1421106.html
Copyright © 2011-2022 走看看