如果我有一个名为MyProgram的类,是否有一种方法检索“MyProgram”作为字符串?
当前回答
获取Asp.net的当前类名
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
其他回答
这个可以省略。所有你需要得到当前类名的是:
GetType().Name
在c# 6.0中,你可以使用操作符的名称:
nameof(MyProgram)
虽然micahtan的答案很好,但它在静态方法中不起作用。如果你想检索当前类型的名称,这个方法应该在任何地方都适用:
string className = MethodBase.GetCurrentMethod().DeclaringType.Name;
获取Asp.net的当前类名
string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();
如果你在派生类中需要这个,你可以把这个代码放在基类中:
protected string GetThisClassName() { return this.GetType().Name; }
然后,您可以在派生类中找到该名称。返回派生类名。当然,当使用新的关键字“nameof”时,就不需要这样的变化行为了。
此外,你可以这样定义:
public static class Extension
{
public static string NameOf(this object o)
{
return o.GetType().Name;
}
}
然后像这样使用:
public class MyProgram
{
string thisClassName;
public MyProgram()
{
this.thisClassName = this.NameOf();
}
}
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 如何使用JSON确保字符串是有效的JSON。网
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 如何检查IEnumerable是否为空或空?
- 自动化invokerrequired代码模式
- 在c#代码中设置WPF文本框的背景颜色
- 在c#中,什么是单子?
- c#和Java中的泛型有什么不同?和模板在c++ ?
- c#线程安全快速(est)计数器
- 如何将此foreach代码转换为Parallel.ForEach?
- 如何分裂()一个分隔字符串到一个列表<字符串>
- 如何转换列表<字符串>列表<int>?
- c#对象列表,我如何得到一个属性的和