C
Chuck Bowling
Is there some way to determine what base class an instance of a object was
derived from?
derived from?
Roy Fine said:Chuck
get the type of the object of interest, then use the BaseType property.
Consider something like this:
static void PrintHeirarchy(object o){
Type t = o.GetType();
string curName = t.FullName;
string baseName = t.BaseType.FullName;
Console.WriteLine("Cur Type: {0}\nBase Type: {1}",curName,baseName);
}
regards
roy fine
Nicholas Paldino said:Rather, you should do this:
// Get the type.
Type t = o.GetType();
do
{
string p = padds.PadRight(indent*2,' ');
Console.WriteLine("{0}Class: {1}",p,t.FullName);
indent++;
t = t.BaseType;
} while (t != null)
Using just a value of true in a loop construct is pretty bad practice.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Roy Fine said:and if you want to view the entire heirarchy - try something like this:
static void PrintHeirarchy(object o){
int indent = 0;
string padds = "";
Type t = o.GetType();
while(true){
string p = padds.PadRight(indent*2,' ');
Console.WriteLine("{0}Class: {1}",p,t.FullName);
t = t.BaseType;
if(t == null) break;
indent++;
}
}
regards
roy fine
object
was
James Curran said:Well, since we're trying to drag every last bit of improvement out of
this.....
--Why are we needlessly dragging multiplication into this?
--Why are we incrementing indent so far from where we are using it?
--Why are we doing something bizarre like padding an empty string when
there's a perfectly good ctor to do what we want?
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.