編輯:我更新了一些更詳細的信息的答案。
下面是一個例子,說明如何完成你想要做的事情。
首先爲您的不同類型的插件類型定義一個枚舉。
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;
}
}
}
}
如果已經定義了「默認」資源,資源文件(如果按名稱命名(name.lang.resx))應自動爲當前語言加載。框架爲你做。爲什麼你需要手動加載資源? – 2011-06-15 08:28:19
因爲這些資源文件被編譯成一個程序集,並且有很多。例如,我有程序集Skin1和Skin2,並且配置表明應用程序使用Skin1,所以應用程序不應該自動加載它們。但是,應用程序必須知道Skin2的存在,以便用戶可以選擇它。 – 2011-06-15 08:33:00
是否有可能以某種接口(ISkin?)的形式實現皮膚,所以你在一個DLL中編寫自己的實現,並向該DLL添加必要的資源?對於每個外觀,您將擁有一個裝配體,並且該裝配體所需的所有資源都是自動加載的。您只需要擔心兩個皮膚不會使用名稱相同的資源(通過在命名約定中添加皮膚名稱很容易防止)。 – 2011-06-15 08:37:13