我需要能够用自定义属性装饰一个 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 循环中,如果我打开调试器并检查“属性”集合,它正确包含 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();
}
...
感谢您提供的任何见解...