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

2023-09-03 00:13:58 作者:高价出售本人脑子,没有用过,有意者私。下面小编为小伙伴们设计

我目前正在开发使用内置的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!")

我希望看到在日志中:

I expect to see in the log:

TestClass, TestMethod, log this!

而是我得到了

But instead I got

TracerClass, LogInfo, log this!

如何获得父类的方法和类的名称?

How to get the parent method and class name?

推荐答案

最新C#和VS 2012附带的来电信息(即 CallerFilePathAttribute CallerLineNumberAttribute CallerMemberNameAttribute ),这将帮助你,如果你只能用它。

The newest C# and VS 2012 shipped with Caller Information (namely CallerFilePathAttribute, CallerLineNumberAttribute and CallerMemberNameAttribute), which will help you if you can only use it.

如果你不能,你必须参考其他的答案。

If you can't, you'd have to refer to other answers.