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
     

  • 相关阅读:
    python新建以时间命名的目录
    selenium跳过https的问题
    selenium修改控件属性
    selenium遍历控件集合
    知识库系统confluence5.8.10 安装与破解
    python3 遍历文件
    mysql更新密码为空
    CentOS7下安装配置vncserver
    Centos7搭建php+mysql环境(整理篇)
    centos7上安装与配置Tomcat7(整理篇)
  • 原文地址:https://www.cnblogs.com/FlyCat/p/2579989.html
Copyright © 2011-2022 走看看