1

カスタム属性で 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();
            }
          ...

あなたが持っているかもしれない洞察をありがとう...

4

1 に答える 1

1
foreach (Attribute attr in attributes)
{
   var devAttr = attr as DeveloperAttribute;
   if (devAttr != null)
   {
      string value = devAttr.Name;
   }
}
于 2012-12-23T23:14:13.970 に答える