在运行时查询dll中的自定义属性

时间:2012-12-23 23:10:05

标签: c# .net

我需要能够使用自定义属性修饰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();
            }
          ...

感谢您有任何见解......

1 个答案:

答案 0 :(得分:1)

foreach (Attribute attr in attributes)
{
   var devAttr = attr as DeveloperAttribute;
   if (devAttr != null)
   {
      string value = devAttr.Name;
   }
}
相关问题