在运行时查询dll中的自定义属性
本文关键字:自定义属性 dll 运行时 查询 | 更新日期: 2023-09-27 17:49:17
我需要能够用自定义属性装饰DLL,然后在运行时从另一个应用程序读取它们。
我有一个名为"QueryDLL"的"主"应用程序。它通过以下代码查询dll:
String assemblyName;
assemblyName = @"..'GenericControl.Dll";
Assembly a = Assembly.LoadFrom(assemblyName);
Type type = a.GetType("GenericControl.UserControl1", true);
System.Reflection.MemberInfo info = type;
var attributes = info.GetCustomAttributes(false);
foreach (Attribute attr in attributes)
{
string value = attr.Name; <----- This of course fails as attr is not of type "GenericControl.UserControl1" - How do I get access "name" field here...
}
我对如何从dll中的属性装饰中获得单个字段(例如名称字段)感到困惑。(我查了其他的例子,但我不清楚……我怀疑我错过了一些简单的?)
在上面的foreach循环中,如果我打开调试器,并检查"attributes"集合,它正确地包含了dll中包含的4个属性装饰,但我无法取出单个字段(名称,级别,审查)。
我的DLL包含一个定义属性的类:
[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class DeveloperAttribute : Attribute
{
// Private fields.
private string name;
private string level;
private bool reviewed;
// This constructor defines two required parameters: name and level.
public DeveloperAttribute(string name, string level)
{
this.name = name;
this.level = level;
this.reviewed = false;
}
// Define Name property.
// This is a read-only attribute.
public virtual string Name
{
get { return name; }
}
// Define Level property.
// This is a read-only attribute.
public virtual string Level
{
get { return level; }
}
// Define Reviewed property.
// This is a read/write attribute.
public virtual bool Reviewed
{
get { return reviewed; }
set { reviewed = value; }
}
}
这个DLL也用这个属性来修饰:
namespace GenericControl
{
[DeveloperAttribute("Joan Smith", "42", Reviewed = true)]
[DeveloperAttribute("Bob Smith", "18", Reviewed = false)]
[DeveloperAttribute("Andy White", "27", Reviewed = true)]
[DeveloperAttribute("Mary Kline", "23", Reviewed = false)]
public partial class UserControl1: UserControl
{
public UserControl1()
{
InitializeComponent();
}
...
foreach (Attribute attr in attributes)
{
var devAttr = attr as DeveloperAttribute;
if (devAttr != null)
{
string value = devAttr.Name;
}
}