教程集 www.jiaochengji.com
教程集 >  脚本编程  >  Asp.net  >  正文 c# 反射加载的实例代码

c# 反射加载的实例代码

发布时间:2016-01-19   编辑:jiaochengji.com
学习c#中关于反射的加载,通过一个例子,帮助大家理解,有需要的朋友可以参考下。

三个程序集:
主程序集:BaseApp.exe
接口程序集:IBaseApplication
插件程序集:TestAttri

在接口程序中:
接口:IApp
属性定义:ModuleAttribute
 

复制代码 代码示例:
public interface IApp : IMothed
{
void ParentForm(IApp frm);
}
namespace IBaseApplication.Attributes
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Interface | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Class | AttributeTargets.Property, AllowMultiple = true, Inherited = false)]
public class ModuleAttribute : Attribute
{
public string IdName { get; set; }
public string ModuleName { get; set; }
public Type ModuleType { get; set; }
//public string AsmName { get; set; }
//public string ClassName { get; set; }
public string Description { get; set; }
}
}

在插件程序集中:
在该插件程序集中的AssemblyInfo类中标识如下
 

复制代码 代码示例:
[assembly: IBaseApplication.Attributes.Module(ModuleType = typeof(UserControl1), IdName = "be4d9a5b-0455-4e9d-a255-25122b80bef1-UserControl1", ModuleName = "UserControl1", Description = "")]
[assembly: IBaseApplication.Attributes.Module(ModuleType = typeof(UserControl2), IdName = "be4d9a5b-0455-4e9d-a255-25122b80bef1-UserControl2", ModuleName = "UserControl2", Description = "")]

两个模块
 

复制代码 代码示例:
namespace TestAttri
{
public partial class UserControl1 : UserControl, IApp
{
……
}
}
namespace TestAttri
{
public partial class UserControl2 : UserControl, IApp
{
……
}
}

在主程序集中:
将插件放至到:Application.StartupPath + "\\Plus"
引用了接口程序集“IBaseApplication”
 

复制代码 代码示例:
/// <summary>
/// 获取插件文件名称
/// </summary>
/// <returns></returns>
public string[] GetPlusFiles()
{
return System.IO.Directory.GetFiles(Application.StartupPath + "\\Plus");
}
/// <summary>
/// 加载插件
/// </summary>
public void LoadPluFiles()
{
string[] files = GetPlusFiles();
Assembly assembly = Assembly.GetCallingAssembly();
foreach (string file in files)
{
ModuleAttribute[] attributes = Assembly.LoadFile(file).GetCustomAttributes(typeof(ModuleAttribute), false) as ModuleAttribute[];
foreach (ModuleAttribute attribute in attributes)
{
string m = attribute.ModuleType.FullName;
string m1 = attribute.ModuleType.Assembly.GetName().Name;
object obj = Activator.CreateInstance(attribute.ModuleType);
if (obj is IApp)
{//无法识别两个模块的接口。
}
}
}
}

您可能感兴趣的文章:
C#学习笔记之反射举例
c#反射实例学习
C#反射实例学习入门及注意事项

您可能感兴趣的文章:
Java反射(泛型擦除演示)的例子
C#反射实例学习入门及注意事项
c#反射实例学习
c# 反射加载的实例代码
C#反射的一些基本应用
C#学习笔记之反射举例
c#反射调用类型成员的例子
golang 映射 map 简介
C#反射的使用方法
C#反射技术(读取和设置类的属性)的例子

关键词: 反射   
[关闭]
~ ~