代码之家  ›  专栏  ›  技术社区  ›  Nick Allen

通过代码访问静态类的类名有什么方法吗?

c#
  •  4
  • Nick Allen  · 技术社区  · 16 年前

    在静态类中,不能使用关键字“this”,因此我不能调用 this.GetType().GetFullName 如果我有

    public static class My.Library.Class
    {
        public static string GetName()
        {
        }
    }
    

    在getname中有什么可以调用的东西可以返回我的.library.class吗

    3 回复  |  直到 16 年前
        1
  •  4
  •   Rob Fonseca-Ensor    16 年前

    您可以通过以下方式获得预定类的类型:

    typeof(My.Library.Class).FullName
    

    如果需要“声明此方法的类”,则需要使用

    MethodBase.GetCurrentMethod().DeclaringType.FullName
    

    然而,这种方法有可能 will be inlined by the compiler . 您可以将此调用转移到类的静态构造函数/初始化器(永远不会内联-log4net建议使用此方法):

    namespace My.Library
    
        public static class Class
        {
            static string className = MethodBase.GetCurrentMethod().DeclaringType.FullName;
            public static string GetName()
            {
                 return className;
            }
        }
    }
    

    应用 [MethodImpl(MethodImplOptions.NoInlining)] 可能会有帮助,但你真的应该 read up on that if you considering it

    Rob

        2
  •  1
  •   Aen Sidhe    16 年前
    MethodBase.GetCurrentMethod().DeclaringType.FullName
    
        3
  •  1
  •   Steven    16 年前
    typeof(My.Library.Class).FullName