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
     

  • 相关阅读:
    jvm gc 日志详细信息的输出(一)
    带宽与数据传输速率
    功率半导体器件
    超链接标签a样式生效,取消下划线,文字垂直(上下)居中
    防范诈骗
    去掉table中的空隙
    html中使用js实现内容过长时部分
    背景色透明度设置
    jQuery给标签写入内容
    多个div居中显示
  • 原文地址:https://www.cnblogs.com/FlyCat/p/2579989.html
Copyright © 2011-2022 走看看