zoukankan      html  css  js  c++  java
  • .NET 反射机制

    一般反射接口定义在单独一个程序集内,第三方程序集引用接口并实现接口,并在宿主通过反射得到类型调用

    接口程序集:

       ILog接口:

        public interface ILog
        {
            void WriteErrorEvent(string errorMessage);
            void WriteApplicationEvent(string applicationMessage);
            void WriteSecurityEvent(string securityMessage);
        }

    第三方程序集:

    public class MyLog:ILog
        {
            public void WriteErrorEvent(string errorMessage)
            {
                Console.WriteLine("error: " + errorMessage);
            }
            public void WriteApplicationEvent(string applicationMessage)
            {
                Console.WriteLine("application: " + applicationMessage);
            }
            public void WriteSecurityEvent(string securityMessage)
            {
                Console.WriteLine("security: " + securityMessage);
            }
    
        }

    宿主调用:

                Assembly asm = Assembly.LoadFrom(@"Log.dll");
                ILog logger = null;
    
                foreach (Type t in asm.GetTypes())
                {
                    if (t.GetInterface("ILog") != null)
                    {
                        logger = (ILog)Activator.CreateInstance(t);
                        break;
                    }
                }
                if (logger != null)
                {
                    logger.WriteApplicationEvent("Initialized1...");
                }


    但是以上方式很低效,因为它对每种类型进行迭代,并询问加载程序以加载它。

    更好的方式是通过自定义程序集或配置文件来完成:

    在MyLog中定义特性

        [AttributeUsage(AttributeTargets.Assembly)]
        public class LogInterfaceTypeAttribute : System.Attribute
        {
            public readonly string TypeName;
    
            public LogInterfaceTypeAttribute(string typeName)
            {
                TypeName = typeName;
            }
        } 

    在MyLog程序集中添加特性(Properties文件夹中的AssemblyInfo.cs文件)

    [assembly: LogInterfaceType("Log.MyLog")]

    加载方式

                Assembly asm = Assembly.LoadFrom(@"Log.dll");
                LogInterfaceTypeAttribute logtype = (LogInterfaceTypeAttribute)
                asm.GetCustomAttributes(typeof(LogInterfaceTypeAttribute), false)[0];
                ILog log = (ILog)
                Activator.CreateInstance(asm.GetType(logtype.TypeName));
                log.WriteApplicationEvent("Initialized2...");

     示例文件

    https://files.cnblogs.com/FlyCat/SimpleReflector.zip
     

  • 相关阅读:
    0004- NTFS FAT32
    0003-SQLServer 安装硬件要求
    php文件上传
    PHP 全局变量
    PHP 数组和数组排序
    PHP 函数
    PHP判断语句及循环语句
    PHP(一)
    HTTP请求组成
    扫描器的意义和利用思维
  • 原文地址:https://www.cnblogs.com/FlyCat/p/2579989.html
Copyright © 2011-2022 走看看