【问题标题】:How to get class name in code as static string property如何在代码中获取类名作为静态字符串属性
【发布时间】:2013-08-19 15:57:38
【问题描述】:

我想得到这样的东西:

public class myclass()
{
    public static string ClassName { get { return "myclass"; } }        
}

有没有一种通用的方法可以将上面代码示例中的字符串“myclass”替换为所属类的名称? 我知道我们可以以非静态方式做到这一点:

    public string ClassName { get { return this.GetType().Name; } }        

但在静态?

【问题讨论】:

  • 你可以在静态对象上调用 getType,但不知道你为什么要公开你的类名
  • @Sayse 甚至让它“静态”。我的意思是它在编译时是静态的,不是吗?

标签: c# class static gettype


【解决方案1】:
class Test
{
       public static string ClassName
       {
          get
          {
             return MethodBase.GetCurrentMethod().DeclaringType.Name;
          }
       } 
}

【讨论】:

  • 如果任何类派生自 Test 并询问类名,这将不起作用。它总是返回 Test 而不是具体的类。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-16
  • 1970-01-01
  • 2023-03-13
  • 2016-04-10
  • 1970-01-01
相关资源
最近更新 更多