Home > Blockchain >  Load an Assembly and get a custom attribute from specific methods
Load an Assembly and get a custom attribute from specific methods

Time:08-18

I have a code snip that I load a dll and I am trying to get a custom attribute type. The custom type is declared in the SomeDll

// SomeDll.dll
[SomeCustomAttribute]
public void Foo()
{
}

This is the second project below

public static void Main(string[] args)
{
   string dllPath = @".\SomeDll.dll";

   var assembly = Assembly.LoadFrom(dllPath);

   var testMethods = assembly.GetTypes()
      .SelectMany(t => t.GetMethods())
      .Where(m => m.GetCustomAttributes("HOW CAN I GET SomeCustomAttribute HERE?")
      .ToArray();
}

CodePudding user response:

The easiest is to loop the attributes returned by GetCustomAttributes and check their names:

var testMethods = assembly.GetTypes()
    .SelectMany(t => t.GetMethods())
    .Where(m => m.GetCustomAttributes(false).FirstOrDefault()?.GetType().Name == "SomeCustomAttribute")
    .ToArray();

Alternativly you may first get the type of the attribute and use that for GetCustomAttributes:

var type = assembly.GetType("The.Namespace.SomeCustomAttribute");
var testMethods = assembly.GetTypes()
    .SelectMany(t => t.GetMethods())
    .Where(m => m.GetCustomAttributes(type, false).Any())
    .ToArray();
  • Related