一般反射接口定义在单独一个程序集内,第三方程序集引用接口并实现接口,并在宿主通过反射得到类型调用
接口程序集:
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(@"MyLog.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("Initialized...");
但是以上方式很低效,因为它对每种类型进行迭代,并询问加载程序以加载它。
更好的方式是通过自定义程序集或配置文件来完成:
在MyLog中定义特性
[AttributeUsage(AttributeTargets.Assembly)]
public class LogInterfaceTypeAttribute : System.Attribute
{
public readonly string TypeName;
public LogInterfaceTypeAttribute(string typeName)
{
TypeName = typeName;
}
}
在MyLog程序集中添加特性
[assembly: LogInterfaceType("ClassLibrary.MyLog")]
namespace ClassLibrary
{
public class MyLog:ILog
加载方式
Assembly asm = Assembly.LoadFrom(@"MyLog.dll");
LogInterfaceTypeAttribute logtype = (LogInterfaceTypeAttribute)
asm.GetCustomAttributes(typeof(LogInterfaceTypeAttribute), false)[0];
ILog log = (ILog)
Activator.CreateInstance(asm.GetType(logtype.TypeName));
int i = 0;
log.WriteApplicationEvent("Initialized2...");