mardi 9 mai 2017

How to get the name of the variable calling the current method in C# pre version 6 [duplicate]

This question already has an answer here:

We need to implement custom software analytics to trace the usage of the application. We have a common Command base class so the idea if to trace there something that allows us to know which command has been executed.

Consider the following sample code on a WPF Window with 1 Button:

public partial class MainWindow : Window
{
    private readonly Command _commandName = new Command();

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        _commandName.Execute();
    }
}

public class Command
{
    public void Execute()
    {
        MessageBox.Show(this.GetCommandName());
        // ....
    }

    private string GetCommandName()
    {
        string commandName = null;

        MethodBase method = new StackTrace(new StackFrame(2)).GetFrame(0).GetMethod();
        Type callingType = method.DeclaringType;

        if (callingType != null)
        {
            IList<FieldInfo> variables = callingType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.GetField | BindingFlags.Instance).Where(f => f.FieldType == typeof(Command)).ToList();

            if (variables.Count == 1)
            {
                commandName = variables[0].Name;
            }
        }

        return commandName;
    }
}

This code will show the variable name but only if there is one Command variable on the calling type. Is there a way of getting the calling variable name directly without going thru reflection?





Aucun commentaire:

Enregistrer un commentaire