如何确定调用方法和类名?

编程入门 行业动态 更新时间:2024-10-27 10:23:16
本文介绍了如何确定调用方法和类名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在使用内置的 TraceListener 开发应用程序日志库.这个库将在许多项目中使用,应该提供一个简单的界面,我只需要关心将要写入日志文件的内容,而不是如何写入.

I'm currently developing a application logging library using the built in TraceListener. This library will be used in many projects and should offer a simple interface where I only have to care about WHAT is going to be written in into the log file, but not HOW.

通过使用反射命名空间,我可以找出当前调用日志函数的应用程序(检索执行程序集名称),但我还想要调用日志函数的函数和类的名称.

By using the reflection namespace, I can figure out which application currently called a log function (retrieving execution assembly name), but I want also the name of the function and class that called the logging function.

假设我有:

public static void LogInfo(string vLogText) { Trace.WriteLine( MethodInfo.GetCurrentMethod().Name + this.GetType().ToString() + vLogText); }

当我从另一个项目调用时(类:TestClass,方法:TestMethod)

When I call from another project (class: TestClass, method: TestMethod)

Tracer.LogInfo("log this!")

我希望在日志中看到:

TestClass, TestMethod, log this!

但是我得到了

TracerClass, LogInfo, log this!

如何获取父方法和类名?

How to get the parent method and class name?

推荐答案

尝试这样做:

var mth = new StackTrace().GetFrame(1).GetMethod(); var cls = mth.ReflectedType.Name; // where 1 illustrates how deep into the stack to reflect.

C# 5.0 中有更优雅的解决方案>,但是如果您使用的是较旧的框架,以上内容会有所帮助.

There are more elegant solutions in C# 5.0 >, however if you are using older frameworks, the above will help.

更多推荐

如何确定调用方法和类名?

本文发布于:2023-11-11 23:53:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1579899.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!