Csharp/C#教程:如何查找调用方法C#的完整名称分享


如何查找调用方法C#的完整名称

如何在c#中找到调用方法的全名。 我见过解决方案:

我如何在C#中获取调用方法

如何找到调用当前方法的方法?

从Called函数获取调用函数名称

但他们只给我顶级水平。 考虑这个例子:

namespace Sandbox { class Program { static void Main(string[] args) { test(); } static void test() { var stackTrace = new StackTrace(); var methodBase = stackTrace.GetFrame(1).GetMethod(); Console.WriteLine(methodBase.Name); } } } 

这只是输出’Main’如何让它打印’Sandbox.Program.Main’?

在任何人开始询问我为什么需要使用它之前,它是一个我正在处理的简单日志框架。

编辑

添加到Matzi的答案:

这是解决方案:

 namespace Sandbox { class Program { static void Main(string[] args) { test(); } static void test() { var stackTrace = new StackTrace(); var methodBase = stackTrace.GetFrame(1).GetMethod(); var Class = methodBase.ReflectedType; var Namespace = Class.Namespace; //Added finding the namespace Console.WriteLine(Namespace + "." + Class.Name + "." + methodBase.Name); } } } 

像它应该生成’Sandbox.Program.Main’

这就像这里 。

 MethodBase method = stackTrace.GetFrame(1).GetMethod(); string methodName = method.Name; string className = method.ReflectedType.Name; Console.WriteLine(className + "." + methodName); 

我认为获得全名的最佳方式是:

  this.GetType().FullName + "." + System.Reflection.MethodBase.GetCurrentMethod().Name; 

或试试这个

 string method = string.Format("{0}.{1}", MethodBase.GetCurrentMethod().DeclaringType.FullName, MethodBase.GetCurrentMethod().Name); 

如果要显示最近的函数调用,可以使用:

 StackTrace st = new StackTrace(); StackFrame sf = st.GetFrame(0); var methodName = sf.GetMethod(); 

,但如果要显示调用函数树,可以这样做:

 if (st.FrameCount >1) { // Display the highest-level function call // in the trace. StackFrame sf = st.GetFrame(st.FrameCount-1); Console.WriteLine(" Original function call at top of call stack):"); Console.WriteLine(" {0}", sf.GetMethod()); } 

了解更多信息

System.Reflection.MethodBase方法GetCurrentMethod您可以找到有关使用类等的callstack的完整信息

使用此方法,您可以可靠地获取全名

  public void HandleException(Exception ex, [CallerMemberName] string caller = "") { if (ex != null) { while (ex.InnerException != null) ex = ex.InnerException; foreach (var method in new StackTrace().GetFrames()) { if (method.GetMethod().Name == caller) { caller = $"{method.GetMethod().ReflectedType.Name}.{caller}"; break; } } Console.WriteLine($"Exception: {ex.Message} Caller: {caller}()"); } } 

当前调用命名空间,它不等于当前命名空间

上述就是C#学习教程:如何查找调用方法C#的完整名称分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

  var mNamespace = new StackTrace().GetFrames()?.Select(x => { try { return x.GetMethod().ReflectedType?.Namespace; } catch (Exception) { return string.Empty; } }).First(x => x != new StackTrace().GetFrame(0).GetMethod().ReflectedType?.Namespace); 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/958188.html

(0)
上一篇 2021年11月22日
下一篇 2021年11月22日

精彩推荐