获取当前类';s的姓名
本文关键字:获取 | 更新日期: 2023-09-27 17:59:32
我有以下类:
public class dlgBoughtNote : dlgSpecifyNone
{
public com.jksb.reports.config.cases.BoughtNoteReport _ReportSource;
public dlgBoughtNote()
{
btnPreview.Click += new EventHandler(Extended_LaunchReport);
this.Text = "Bought Note Print";
}
protected override void InitReport()
{
_ReportSource = new com.jksb.reports.config.cases.BoughtNoteReport(null);
ReportSourceName = _ReportSource;
}
}
从技术上讲,如果我调用以下构造函数dlgBoughtNote()
public dlgBoughtNote()
{
btnPreview.Click += new EventHandler(Extended_LaunchReport);
this.Text = "Bought Note Print";
MessageBox.Show(this.Name);
}
我应该得到"dlgBoughtNote"的结果,但我得到的是"dlgSpecifyNone"。除了我现在这样做之外,还有什么方法可以得到当前类的名称吗。
获取当前类名称的最简单方法可能是this.GetType().Name
。
您可以在this
上调用GetType()
来获取实例的类型,并使用类型的Name
属性来获取当前类型的名称。调用this.GetType()
返回的是实例化的类型,而不是定义当前执行方法的类型,因此在基类中调用它将为您提供创建this
的派生子类的类型。
有点困惑。。。这里有一个例子:
public class BaseClass
{
public string MyClassName()
{
return this.GetType().Name;
}
}
public class DerivedClass : BaseClass
{
}
...
BaseClass a = new BaseClass();
BaseClass b = new DerivedClass();
Console.WriteLine("{0}", a.MyClassName()); // -> BaseClass
Console.WriteLine("{0}", b.MyClassName()); // -> DerivedClass
您从未告诉过我们您的this.Name
是什么。但是,如果您需要获得运行时类型名称,那么您可以使用上面的任何答案。只是:
this.GetType().Name
任何你喜欢的组合。
然而,我想,您试图做的是拥有一个属性,为任何派生类(或基类)返回一些特定的值。然后,您需要至少有一个protected virtual
属性,需要在每个派生类中重写该属性:
public class dlgSpecifyNone
{
public virtual string Name
{
get
{
return "dlgSpecifyNone";//anything here
}
}
}
public class dlgBoughtNote : dlgSpecifyNone
{
public override string Name
{
get
{
return "dlgBoughtNote";//anything here
}
}
}
但如果this.GetType().Name
解决了这个问题,这显然是没有必要的。
以下是我的操作方法,我一直将其用于我的记录器:
using System.Reflection;
//...
Type myVar = MethodBase.GetCurrentMethod().DeclaringType;
string name = myVar.Name;