-
-
Notifications
You must be signed in to change notification settings - Fork 625
HOWTO
pkrukp edited this page Jun 9, 2021
·
6 revisions
- Open a module and print its public types
- Check if a type has a certain custom attribute
- Insert an IL instruction before another
public void PrintTypes (string fileName)
{
ModuleDefinition module = ModuleDefinition.ReadModule (fileName);
foreach (TypeDefinition type in module.Types) {
if (!type.IsPublic)
continue;
Console.WriteLine (type.FullName);
}
}
public static bool TryGetCustomAttribute (TypeDefinition type,
string attributeType, out CustomAttribute result)
{
result = null;
if (!type.HasCustomAttributes)
return false;
foreach (CustomAttribute attribute in type.CustomAttributes) {
if (attribute.AttributeType.FullName != attributeType)
continue;
result = attribute;
return true;
}
return false;
}
For a type defined as:
[Foo.Ignore ("Not working yet")]
public class Fixture {
}
Usage:
public static string GetIgnoreReason (TypeDefinition type)
{
CustomAttribute ignoreAttribute;
if (!TryGetCustomAttribute (type, "Foo.IgnoreAttribute", out ignoreAttribute))
return string.Empty;
if (ignoreAttribute.ConstructorArguments.Count != 1)
return string.Empty;
return (string) ignoreAttribute.ConstructorArguments [0].Value;
}
This will insert a call to a method reference as the first instruction in a method body:
var processor = method.Body.GetILProcessor();
var newInstruction = processor.Create(OpCodes.Call, someMethodReference);
var firstInstruction = method.Body.Instructions[0];
processor.InsertBefore(firstInstruction, newInstruction);