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

 示例文件

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

你可能感兴趣的:(.net)