就像标题说的:反射能给你当前正在执行的方法的名字吗?
我倾向于认为不是,因为海森堡的问题。如何调用一个方法,在不改变当前方法的情况下告诉您当前方法?但我希望有人能证明我错了。
更新:
第2部分:这也可以用于在代码中查找属性吗? 第三部分:演出是什么样的?
最终结果 我学习了MethodBase.GetCurrentMethod()。我还了解到,我不仅可以创建堆栈跟踪,还可以只创建我需要的确切帧。
要在属性中使用它,只需使用. substring(4)来删除'set_'或'get_'。
就像标题说的:反射能给你当前正在执行的方法的名字吗?
我倾向于认为不是,因为海森堡的问题。如何调用一个方法,在不改变当前方法的情况下告诉您当前方法?但我希望有人能证明我错了。
更新:
第2部分:这也可以用于在代码中查找属性吗? 第三部分:演出是什么样的?
最终结果 我学习了MethodBase.GetCurrentMethod()。我还了解到,我不仅可以创建堆栈跟踪,还可以只创建我需要的确切帧。
要在属性中使用它,只需使用. substring(4)来删除'set_'或'get_'。
当前回答
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("1: {0} {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);
OtherMethod();
}
public static void OtherMethod()
{
Console.WriteLine("2: {0} {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);
}
}
输出:
1: Main Program
2: OtherMethod Program
其他回答
在空控制台程序的Main方法中试试这个:
MethodBase method = MethodBase.GetCurrentMethod();
Console.WriteLine(method.Name);
控制台输出: 主要
简单的处理方法是:
System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name;
如果系统。反射包含在using块中:
MethodBase.GetCurrentMethod().DeclaringType.FullName + "." + MethodBase.GetCurrentMethod().Name;
using System;
public class Program
{
public static void Main()
{
Console.WriteLine("1: {0} {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);
OtherMethod();
}
public static void OtherMethod()
{
Console.WriteLine("2: {0} {1}", System.Reflection.MethodBase.GetCurrentMethod().Name, System.Reflection.MethodBase.GetCurrentMethod().ReflectedType);
}
}
输出:
1: Main Program
2: OtherMethod Program
我只是用一个简单的静态类做了这个:
using System.Runtime.CompilerServices;
.
.
.
public static class MyMethodName
{
public static string Show([CallerMemberName] string name = "")
{
return name;
}
}
然后在代码中:
private void button1_Click(object sender, EventArgs e)
{
textBox1.Text = MyMethodName.Show();
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = MyMethodName.Show();
}
从。net 4.5开始,你也可以使用[CallerMemberName]。
示例:一个属性setter(回答第2部分):
protected void SetProperty<T>(T value, [CallerMemberName] string property = null)
{
this.propertyValues[property] = value;
OnPropertyChanged(property);
}
public string SomeProperty
{
set { SetProperty(value); }
}
编译器将在调用点提供匹配的字符串字面量,因此基本上没有性能开销。