I have the following class:
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;
}
}
Technically, If I called the following constructor dlgBoughtNote()
public dlgBoughtNote()
{
btnPreview.Click += new EventHandler(Extended_LaunchReport);
this.Text = "Bought Note Print";
MessageBox.Show(this.Name);
}
I should be getting the result as "dlgBoughtNote" but I'm getting as "dlgSpecifyNone". Is there any way I could get the current class's name other than the way I'm doing.
获取当前类名称的最简单方法可能this.GetType().Name
。
You can call GetType()
on this
to get the type of the instance, and use the Name
property of the type to get the current type's name. Calling this.GetType()
returns the type that was instantiated, not the type that defined the currently executing method, so calling it in a base class will give you the type of the derived child class that this
was created from.
A little confusing... here's an example:
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
You've never told us, what your this.Name
is. However, if you need to get the runtime type name, then you may use any of the answers above. That's just:
this.GetType().Name
in any combination you like.
However, I suppose, what you tried to do, was to have a property, returning some certain value for any of the derived (or base) classes. Then you'd need to have at least a protected virtual
property, that you'll need to override in each of the derived classes:
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
}
}
}
But this is obviously unnecessary, if this.GetType().Name
solves this very issue.
Here is how I do it, I use it for my logger all the time:
using System.Reflection;
//...
Type myVar = MethodBase.GetCurrentMethod().DeclaringType;
string name = myVar.Name;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.