How to find the name of the parent class, within a base class in C#?
I inherit a class from a base class "MyLog".
If I call "Write" within the inherited class, I want it to prefix any messages with the name of the inherited class.
As this application needs to be fast, I need some way of avoiding reflection during normal program operation (reflection during startup is fine).
Here is some code to illustrate the point:
class MyClassA : MyLog
{
w("MyMessage"); // Prints "MyClassA: MyMessage"
}
class MyClassB : MyLog
{
w("MyMessage"); // Prints "MyClassB: MyMessage"
}
class MyLog
{
string nameOfInheritedClass;
MyLog()
{
nameOfInheritedClass = ?????????????
开发者_如何学运维}
w(string message)
{
Console.Write(nameOfInheritedClass, message);
}
}
I suspect you want:
nameOfInheritedClass = GetType().Name;
GetType()
always returns the actual type of the object it's called on.
try to explore
this.GetType()
properties in the myLog constructor, there you should be able to find type names and other properties of the correct class hierarchy.
I believe you can use GetType() to achive this.
var parentType = this.GetType().BaseType; //Will return MyLog
Where as Jon Skeet pointed out calling Name
will return the actual type of the object its called on.
精彩评论