c# – .Net 4 – 在程序集中包含自定义信息
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – .Net 4 – 在程序集中包含自定义信息,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2639字,纯文字阅读大概需要4分钟。
内容图文
![c# – .Net 4 – 在程序集中包含自定义信息](/upload/InfoBanner/zyjiaocheng/826/5ce2ae3deff54e6ba71490fb04c223cb.jpg)
我正在构建一个可扩展的应用程序,它将在运行时通过Assembly.LoadFile()加载其他程序集.这些附加程序集将包含诸如WPF资源字典(皮肤等),普通资源(Resx)和/或插件类之类的东西.程序集也可以不包含公共类,只包含资源或资源字典.
我正在寻找一种识别程序集的方法,比如友好名称(如“附加外观”或“集成浏览器”),程序集的功能类型(SkinsLibrary,SkinsLibrary | PluginLibrary等)和其他信息(如ConflictsWith(new [] {“SkinsLibrary”,“BrowserPlugin”).
到目前为止,我在命名程序集中使用约定(* .Skins.* .dll等).在每个程序集中,我有一个空的虚拟类,它只是一个占位符,用于保存实际(程序集范围)信息的自定义类属性,但这感觉就像一个黑客.是否有一些简化的标准方法来处理这个问题?
我正在开发中央加载器系统,我团队中的其他开发人员将开发这些额外的程序集,所以我想最小化约定和管道细节.
解决方法:
编辑:我已经用更详细的信息更新了答案.
这是一个如何完成您想要做的事情的示例.
首先为不同类型的插件类型定义枚举.
public enum AssemblyPluginType
{
Skins,
Browser
}
添加两个将用于描述插件的属性(程序集插件类型和潜在冲突).
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyPluginAttribute : Attribute
{
private readonly AssemblyPluginType _type;
public AssemblyPluginType PluginType
{
get { return _type; }
}
public AssemblyPluginAttribute(AssemblyPluginType type)
{
_type = type;
}
}
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = false)]
public sealed class AssemblyPluginConflictAttribute : Attribute
{
private readonly AssemblyPluginType[] _conflicts;
public AssemblyPluginType[] Conflicts
{
get { return _conflicts; }
}
public AssemblyPluginConflictAttribute(params AssemblyPluginType[] conflicts)
{
_conflicts = conflicts;
}
}
现在,您可以将这些属性添加到程序集中.
只要它们位于命名空间之外,就可以在程序集中的任何位置添加以下两行.我通常将汇编属性放在AssemblyInfo.cs文件中,该文件可以在Properties文件夹中找到.
[assembly: AssemblyPluginAttribute(AssemblyPluginType.Browser)]
[assembly: AssemblyPluginConflictAttribute(AssemblyPluginType.Skins, AssemblyPluginType.Browser)]
现在,您可以使用以下代码检查特定属性的程序集:
using System;
using System.Reflection;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
// Get the assembly we're going to check for attributes.
// You will want to load the assemblies you want to check at runtime.
Assembly assembly = typeof(Program).Assembly;
// Get all assembly plugin attributes that the assembly contains.
object[] attributes = assembly.GetCustomAttributes(typeof(AssemblyPluginAttribute), false);
if (attributes.Length == 1)
{
// Cast the attribute and get the assembly plugin type from it.
var attribute = attributes[0] as AssemblyPluginAttribute;
AssemblyPluginType pluginType = attribute.PluginType;
}
}
}
}
内容总结
以上是互联网集市为您收集整理的c# – .Net 4 – 在程序集中包含自定义信息全部内容,希望文章能够帮你解决c# – .Net 4 – 在程序集中包含自定义信息所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。