lundi 7 octobre 2019

Can custom attributes get the parameters of the method they are attached to?

I have a custom attribute and would like to be able to inspect the signature of the item it is attached to from inside the attribute's code.

This would be easy from outside the attribute, but it specifically needs to be inside the attribute. I've tried traversing StackTrace but this does not get the method I'm attaching to, and CallerMemberName also does not get me what I need.


public class MyAttribute : Attribute
{
  public void ReadDetails()
  {
    MethodInfo attachee = ???; // TODO

    Console.WriteLine(attachee.MethodName); // expect "Baa"
    Console.WriteLine(attachee.GetParameters()[0].ParameterType.Name); // expect "int"
    Console.WriteLine(attachee.GetParameters()[0].Name); // expect "a"
  }
}

public class foo
{
  [MyAttribute]
  public void Baa(int a, string b) {}
}

For context, this is to support some automated testing - I have a spreadsheet of data describing a user interface, and test methods with fewer parameters than the spreadsheet has columns. I have a custom attribute which subclasses NUnit TestCaseSourceAttribute and reads the spreadsheet, but needs to filter the columns down to just what the test case needs. For example I'll have tests like:

[SpreadsheetDrivenTests("ui.xlsx")]
public void TestButtonText(string buttonId, string expectedText) {}

[SpreadsheetDrivenTests("ui.xlsx")]
public void TestButtonVisibility(string buttonId, bool expectedVisible) {}





Aucun commentaire:

Enregistrer un commentaire