C# 如何在c中以字符串形式获取方法名?
在Java中,我们可以使用Java.lang.reflect API中的方法获得方法名。比如说C# 如何在c中以字符串形式获取方法名?,c#,C#,在Java中,我们可以使用Java.lang.reflect API中的方法获得方法名。比如说 public void GetmethodName(Method method) { String testName = method.getName(); } 我可以使用c中的反射API或诊断API实现这一点吗非常类似: 公共void GetMethodNameMethodInfo方法 { 字符串testName=method.Name; } 您可以通过类型实例获取MethodInfo,即t
public void GetmethodName(Method method)
{
String testName = method.getName();
}
我可以使用c中的反射API或诊断API实现这一点吗非常类似:
公共void GetMethodNameMethodInfo方法
{
字符串testName=method.Name;
}
您可以通过类型实例获取MethodInfo,即typeofFoo.GetMethod。。。或someTypeInstance.GetMethods…非常类似:
公共void GetMethodNameMethodInfo方法
{
字符串testName=method.Name;
}
您可以通过类型实例获取MethodInfo,即typeofFoo.GetMethod。。。或者someTypeInstance.GetMethods…可以使用反射获取方法名称:
using System.Reflection;
// ...
public class MyClass
{
public void MyMethod()
{
MethodBase m = MethodBase.GetCurrentMethod();
// This will write "MyClass.MyMethod" to the console
Console.WriteLine($"Executing {m.ReflectedType.Name}.{m.Name}");
}
}
可以使用反射获取方法名称:
using System.Reflection;
// ...
public class MyClass
{
public void MyMethod()
{
MethodBase m = MethodBase.GetCurrentMethod();
// This will write "MyClass.MyMethod" to the console
Console.WriteLine($"Executing {m.ReflectedType.Name}.{m.Name}");
}
}
你可以用
使用CallerMemberNameAttribute时,编译器会在编译期间直接硬代码检查ldstr指令和方法名称,而不需要反射。比如说,
void Foo()
{
GetmethodName();
}
查看IL代码
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldstr "Foo"
IL_0007: call UserQuery.GetmethodName
IL_000C: nop
IL_000D: ret
你可以用
使用CallerMemberNameAttribute时,编译器会在编译期间直接硬代码检查ldstr指令和方法名称,而不需要反射。比如说,
void Foo()
{
GetmethodName();
}
查看IL代码
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldstr "Foo"
IL_0007: call UserQuery.GetmethodName
IL_000C: nop
IL_000D: ret
这里testName的预期值是多少?我不想做任何假设,尽管我想我知道你在追求什么。不要在C 6及以上版本中使用反射,而是使用MethodName的名称。@oh,很多时候基于MethodInfo的反射是完全合适的;实际上,这取决于我们这里没有的上下文。我理解这一点,但我不明白为什么在提到nameof之前我们建议进行反射。这里testName的预期值是多少?我不想做任何假设,尽管我想我知道你在追求什么。不要在C 6及以上版本中使用反射,而是使用MethodName的名称。@oh,很多时候基于MethodInfo的反射是完全合适的;实际上,这取决于我们在这里没有的上下文,我理解这一点,但我不明白为什么我们建议在提到nameof之前进行反射;您只需编写一个静态字符串CurrentMethodName[CallerMemberName]字符串caller=null=>caller;只需执行字符串whoAmI=CurrentMethodName;-或者只是字符串whoAmI=methodyouarein的名称;如果您只是想避免使用字符串文字,如果您在当前方法的名称之后,那么您不会这样做;您只需编写一个静态字符串CurrentMethodName[CallerMemberName]字符串caller=null=>caller;只需执行字符串whoAmI=CurrentMethodName;-或者只是字符串whoAmI=methodyouarein的名称;如果您只是想避免字符串literal,那么IL看起来就像是处于调试模式;如果没有它,它将更加简洁,尤其是如果您使用GetmethodNamestatic@MarcGravell接得好,没错。它处于调试模式。IL看起来好像处于调试模式;如果没有它,它将更加简洁,尤其是如果您使用GetmethodNamestatic@MarcGravell接得好,没错。它处于调试模式。