c# print the class name from within a static function

前端 未结 7 750
囚心锁ツ
囚心锁ツ 2021-02-06 23:19

Is it possible to print the class name from within a static function?

e.g ...

public class foo
{

    static void printName()
    {
        // Print the          


        
相关标签:
7条回答
  • 2021-02-06 23:41

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

    0 讨论(0)
  • 2021-02-06 23:42

    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.

    0 讨论(0)
  • 2021-02-06 23:45

    You have three options to get the type (and therefore the name) of YourClass that work in a static function:

    1. typeof(YourClass) - fast (0.043 microseconds)

    2. MethodBase.GetCurrentMethod().DeclaringType - slow (2.3 microseconds)

    3. new StackFrame().GetMethod().DeclaringType - slowest (17.2 microseconds)


    If using typeof(YourClass) is not desirable, then MethodBase.GetCurrentMethod().DeclaringType is definitely the best option.

    0 讨论(0)
  • 2021-02-06 23:50
    Console.WriteLine(new StackFrame().GetMethod().DeclaringType);
    
    0 讨论(0)
  • 2021-02-06 23:53

    StackTrace class can do that.

    0 讨论(0)
  • 2021-02-06 23:58

    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);
            ...
        }
    }
    
    0 讨论(0)
提交回复
热议问题