c# print the class name from within a static funct

2019-03-17 09:02发布

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
    }

}

标签: c# static
7条回答
闹够了就滚
2楼-- · 2019-03-17 09:37

A (cleaner, IMO) alternative (still slow as hell and I would cringe if I saw this in a production code base):

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.

查看更多
手持菜刀,她持情操
3楼-- · 2019-03-17 09:43

StackTrace class can do that.

查看更多
混吃等死
4楼-- · 2019-03-17 09:44

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:

public class Foo
{
    static void PrintName()
    {
        string className = nameof(Foo);
        ...
    }
}
查看更多
叼着烟拽天下
5楼-- · 2019-03-17 09:47
Console.WriteLine(new StackFrame().GetMethod().DeclaringType);
查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-03-17 09:47

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.

查看更多
祖国的老花朵
7楼-- · 2019-03-17 09:48

Since static methods cannot be inherited the class name will be known to you when you write the method. Why not just hardcode it?

查看更多
登录 后发表回答