c# 从静态函数中打印类名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/552629/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# print the class name from within a static function
提问by TK.
Is it possible to print the class name from within a static function?
是否可以从静态函数中打印类名?
e.g ...
例如...
public class foo
{
static void printName()
{
// Print the class name e.g. foo
}
}
采纳答案by Jamezor
You have three options to get the type (and therefore the name) of YourClass
that work in a static function:
您有三个选项可以YourClass
在静态函数中获取该工作的类型(以及名称):
typeof(YourClass)
- fast (0.043 microseconds)MethodBase.GetCurrentMethod().DeclaringType
- slow (2.3 microseconds)new StackFrame().GetMethod().DeclaringType
- slowest (17.2 microseconds)
typeof(YourClass)
- 快速(0.043 微秒)MethodBase.GetCurrentMethod().DeclaringType
- 慢(2.3 微秒)new StackFrame().GetMethod().DeclaringType
- 最慢(17.2 微秒)
If using typeof(YourClass)
is not desirable, then MethodBase.GetCurrentMethod().DeclaringType
is definitely the best option.
如果使用typeof(YourClass)
不是可取的,那么MethodBase.GetCurrentMethod().DeclaringType
绝对是最好的选择。
回答by Anton Gogolev
StackTraceclass can do that.
StackTrace类可以做到这一点。
回答by Matt Hamilton
Console.WriteLine(new StackFrame().GetMethod().DeclaringType);
回答by Marc Gravell
While the StackTrace answers are correct, they do have an overhead. If you simply want safety against changing the name, consider typeof(foo).Name
. Since static methods can't be virtual, this should usually be fine.
虽然 StackTrace 答案是正确的,但它们确实有开销。如果您只是想安全地避免更改名称,请考虑typeof(foo).Name
. 由于静态方法不能是虚拟的,这通常应该没问题。
回答by Kent Boogaart
A (cleaner, IMO) alternative (still slow as hell and I would cringe if I saw this in a production code base):
一个(更干净的,IMO)替代方案(仍然很慢,如果我在生产代码库中看到这个我会畏缩):
Console.WriteLine(MethodBase.GetCurrentMethod().DeclaringType);
By the way, if you're doing this for logging, some logging frameworks (such as log4net) have the ability built in. And yes, they warn you in the docs that it's a potential performance nightmare.
顺便说一句,如果您这样做是为了记录日志,一些日志框架(例如 log4net)具有内置的功能。是的,他们在文档中警告您这是一个潜在的性能噩梦。
回答by Vilx-
Since static methods cannot be inherited the class name will be known to you when you write the method. Why not just hardcode it?
由于静态方法不能被继承,当您编写方法时,您将知道类名。为什么不直接硬编码呢?
回答by Jamezor
Since C# 6.0 there exists an even simpler and faster way to get a type name as a string without typing a string literal in your code, using the nameof
keyword:
从 C# 6.0 开始,存在一种更简单、更快的方法来获取类型名称作为字符串,而无需在代码中键入字符串文字,使用nameof
关键字:
public class Foo
{
static void PrintName()
{
string className = nameof(Foo);
...
}
}