将变量设置为包含方法的名称

时间:2013-12-12 16:42:26

标签: c#

这应该看起来很简单,但我有时间想象它。让我们说我有一个方法:

public Person person(string firstName, string lastName)
{
    //code and such

    string methodName = "Person person";
}

有没有办法创建变量并动态地将其设置为方法的名称?我需要这个,所以当我调用自定义异常方法时,我可以设置有问题的方法的日志名称。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:7)

您可以使用:

System.Reflection.MethodBase.GetCurrentMethod().Name;

如果您也想要这种类型,可以使用:

var method = System.Reflection.MethodBase.GetCurrentMethod();
var methodName = string.Format("{0} {1}", method.DeclaringType.Name, method.Name);

编辑现在,我发现您正在编写日志记录功能,您可能需要尝试使用MSDN文档中的类似内容:

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [CallerMemberName] string memberName = "",
        [CallerFilePath] string sourceFilePath = "",
        [CallerLineNumber] int sourceLineNumber = 0)
{
    Trace.WriteLine("message: " + message);
    Trace.WriteLine("member name: " + memberName);
    Trace.WriteLine("source file path: " + sourceFilePath);
    Trace.WriteLine("source line number: " + sourceLineNumber);
}

[CallerMemberName]属性表示编译器应该传递调用函数。这使得它比使用反射更快。有关详情,请查看此链接:http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx

答案 1 :(得分:4)

string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;

答案 2 :(得分:2)

使用.NET 4.5的另一种解决方案是使用CallerMemberName属性。

public class Example
{
    public void Foo()
    {
        Bar();
    }

    private void Bar([CallerMemberName] string caller = null)
    {
         Console.WriteLine(caller); //Writes "Foo"
    }
}

它不会显示您所在功能的名称,而是提供给您的功能名称。我不知道这对你的异常处理程序是否有用,但它对于实现INotifyPropertyChanged非常有用

private string _exampleProperty;

public String ExampleProperty
{
    get { return _exampleProperty; }
    set
    {
        if (value == _exampleProperty) return;
        _exampleProperty = value;
        OnPropertyChanged();
    }
}

public event PropertyChangedEventHandler PropertyChanged;

protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
    var handler = PropertyChanged;
    if (handler != null) 
        handler(this, new PropertyChangedEventArgs(propertyName));
}