Reputation: 80272
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);
}
}
Upvotes: 1
Views: 83
Reputation: 5916
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.
Upvotes: 2
Reputation: 44605
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.
Upvotes: 2
Reputation: 1500675
I suspect you want:
nameOfInheritedClass = GetType().Name;
GetType()
always returns the actual type of the object it's called on.
Upvotes: 5