2013-10-02 37 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