C# Determining the type of an object
I'm not exactly sure how to ask this question well. Sorry if it's unclear. I'm trying to determine the type an object is acting as, not the actual type of an object.
Say I have these two classes:
public class A{
public A() {
string thisTypeName = this.GetType().???; // the value I'm looking for here is "A" not "B"
}
}
public class B : A { }
What I do not want is...
string thisTypeName = this.GetType().BaseType.Name;
...because if I decide to do this...
开发者_开发百科public class C : B { }
...then now my this.GetType().BaseType will reference the class B, not A.
Is there a built-in way to do this? I'm guessing I can probably write an extension method on Type that will do what I want.
Watch it with some of the advice you are getting now. Some of that is kind of smelly in my book.
You want to use:
typeof(A).IsAssigneableFrom(aninstance.GetType());
to determine whether a type is derived from a basetype, or implements an interface
See: http://msdn.microsoft.com/en-us/library/system.type.isassignablefrom.aspx. This page has a slew of interesting examples showing all the subtle cases it supports
public static Type GetActualBaseType(this object obj)
{
Type type = obj.GetType();
while (type.IsNested)
type = type.BaseType;
return type;
}
you could attempt to use that
You could use System.Diagnostics.StackTrace
to get the stack frame, and then get the DeclaringType
for the current method:
var st = new StackTrace();
Console.WriteLine(st.GetFrame(0).GetMethod().DeclaringType.ToString());
what you seem to be looking for is known at compile time:
in ctor of B you want the type B
in ctor of A you want the type A ...
so you could simply write typeof(A)
, typeof(B)
, etc
if you want to get the type by reflection that declared the current method:
MethodBase.GetCurrentMethod().DeclaringType
Do you really need a type string of a given class instance, or do you want to know how to handle different child types of a certain base class?
In the latter case, it's probably better to use the is
keyword, like this:
class A {}
class B : A {}
class C : B {}
class Aaa : A {}
// NB: order of if() statements is important below, start with most specific ones
public void doSomething(A obj) {
if(obj is Aaa) {
// do something specific for Aaa
} else if(obj is C) {
// do something specific for C
} else if(obj is B) {
// do something specific for B
} else {
// do general A stuff
}
}
I have no idea if this is where you were trying to go, but from the question you posed and your comment it's clear that just getting the name of the base class is not the real problem.
精彩评论