2013-10-02 33 views
0

我有一個小小的需求,並且在完成它時似乎遇到了一些麻煩。請知道我是c#中的新手,這是給我的任務,我很友善請求大家以最迅速的答覆幫助我,因爲我已經越過了這項任務的最後期限。無法從DLL中獲得自定義屬性的列表

我有一個dll,並且有一個定製的屬性,我希望能夠從使用此定製屬性的類中檢索所有方法。請注意我必須從構建的dll中獲取方法名稱從另一個應用程序

下面是更清晰的代碼。

MY屬性類:

namespace model 
{ 
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)] 
    public sealed class Class1: Attribute 
    { 
     public Class1() 
     {} 
     public Class1(string helptext) 
     { } 
     public string HelpText { get; internal set; } 
    } 
} 

使用該屬性,並且是要被構建爲DLL

private void Form1_Load(object sender, EventArgs e) 
    { 
     Assembly mydllAssembly = Assembly.LoadFile(@"D:\Windowsservice\BasicMEthods\BasicMEthods\bin\Debug\BasicMEthods.dll"); 
     Type mydllFormType = mydllAssembly.GetType("BasicMEthods.Transforms",true); 
     MemberInfo info = mydllFormType; 
     Attribute[] attrs = (Attribute[])info.GetCustomAttributes(true); 
      foreach (Attribute att in attrs) 
      { 
       MethodInfo[] myArrayMethodInfo1 = mydllFormType.GetMethods(BindingFlags.Public); 
        for (int i = 0; i < myArrayMethodInfo1.Length; i++) 
        { 
         MethodInfo mymethodinfo = (MethodInfo)myArrayMethodInfo1[i]; 
         textBox1.Text = mymethodinfo.ToString(); 
        } 
      } 
     } 
} 

的誤差在這條線的拋出後要提取的類代碼

Attribute[] attrs = (Attribute[])info.GetCustomAttributes(true); 

它說

「無法加載文件或程序集」模型,版本= 1.0.0.0,Culture = neutral,PublicKeyToken = null'或其依賴項之一。系統找不到指定的文件。「

該DLL正在從指定的位置獲取,並且我能夠在快速監視中看到類轉換我不知道爲什麼會引發此錯誤...並且還有我不知道我能得到訪問在DLL中定義的屬性....請幫助

+0

有人請幫我看定製從DLL – user2115640

+0

哪裏屬性類型'model'屬性來定義?聽起來就像它在另一個你尚未加載的程序集中。 –

+0

感謝斯蒂芬的答覆...我沒有淹沒模型大會後我意識到它,並把它封鎖但是你可以請讓我知道我如何得到方法裝飾自定義屬性從DLL ...在此先感謝 – user2115640

回答

0

這個方法應該做的伎倆:

private List<MethodInfo> FindMethodsWithAttribute(Type T,Type AT) 
{ 
    var result = new List<MethodInfo>(); 
    //get all the methods on type T that are public instance methods 
    var methods=t.GetMethods(BindingFlags.Public); 
//loop them 
foreach (var method in methods) 
    { 
    //get the list of custom attributes, if any, of type AT 
     var attributes = method.GetCustomAttributes(AT); 
     if (attributes.Length!=0) result.AddRange(attributes); 
    } 
} 

,並調用它是這樣的:

var methods = FindMethodsWithAttribute(mydllFormType ,typeof(model)); 

我會留下作爲一個練習自己揣摩出在現有的代碼上面應該去:)

+0

感謝噸我碰巧c這只是現在....再次感謝 – user2115640

+0

沒問題,不要忘了接受答案,如果它適合你! –

+0

你好,我發現一個問題,因爲它的DLL通過模型,有沒有另一種方式,或者可能是我不明白它的正確方式....,你可以幫助...在此先感謝 – user2115640