In C#, using reflection, is it possible to define method in the base class that returns its own name (in the form of a string) and have subclasses inherit this behavior in a polymorphic way?
For example:
public class Base
{
public 开发者_C百科string getClassName()
{
//using reflection, but I don't want to have to type the word "Base" here.
//in other words, DO NOT WANT get { return typeof(Base).FullName; }
return className; //which is the string "Base"
}
}
public class Subclass : Base
{
//inherits getClassName(), do not want to override
}
Subclass subclass = new Subclass();
string className = subclass.getClassName(); //className should be assigned "Subclass"
public class Base
{
public string getClassName()
{
return this.GetType().Name;
}
}
actually, you don't need to create a method getClassName() just to get the type-name
. You can call GetType() on any .Net object and you'll get the meta information of the Type.
You can also do it like this,
public class Base
{
}
public class Subclass : Base
{
}
//In your client-code
Subclass subclass = new Subclass();
string className = subclass.GetType().Name;
EDIT
Moreover, should you really need to define getClassName() in any case, I'd strongly suggest to make it a property [as per .net framework design guide-lines] since the behavior of getClassName() is not dynamic and it will always return the same value every-time you call it.
public class Base
{
public string ClassName
{
get
{
return this.GetType().Name;
}
}
}
EDIT2
Optimized version After reading comment from Chris.
public class Base
{
private string className;
public string ClassName
{
get
{
if(string.IsNullOrEmpty(className))
className = this.GetType().Name;
return className;
}
}
}
精彩评论