c#从静态函数中打印类名

是否可以在静态函数中打印类名?

例如……

public class foo { static void printName() { // Print the class name eg foo } } 

 Console.WriteLine(new StackFrame().GetMethod().DeclaringType); 

您有三个选项来获取在静态函数中工作的YourClass的类型(以及名称):

  1. typeof(YourClass) – 快速(0.043微秒)

  2. MethodBase.GetCurrentMethod().DeclaringType – 慢(2.3微秒)

  3. new StackFrame().GetMethod().DeclaringType 17.2微秒)

如果不希望使用typeof(YourClass) ,那么MethodBase.GetCurrentMethod().DeclaringType绝对是最佳选择。

虽然StackTrace答案是正确的,但它们确实有开销。 如果您只想安全地改变名称,请考虑typeof(foo).Name 。 由于静态方法不能是虚拟的,因此通常应该没问题。

一个(更清洁,IMO)的替代方案(如果我在生产代码库中看到这个,我会很畏缩)

 Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType); 

顺便说一句,如果你正在进行日志记录,一些日志记录框架(例如log4net)具有内置的能力。是的,他们在文档中警告你,这是一个潜在的性能噩梦。

StackTrace类可以做到这一点。

由于无法inheritance静态方法,因此在编写方法时您将知道类名。 为什么不直接硬编码呢?