C#反射学习

本文介绍了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");

        }

    }

}

 

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

转载于:https://www.cnblogs.com/saper/archive/2009/03/25/1421106.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值