选项 1 :: 获取“容器”类:
/**CODE**/
public static void Main(string[] args)
{
B c = new C();
Test(c);
Console.ReadKey();
}
public static void Test(A a) { Console.WriteLine(typeof(A).ToString()); }
public static void Test(B b) { Console.WriteLine(typeof(B).ToString()); }
public static void Test(C c) { Console.WriteLine(typeof(C).ToString()); }
/**OUTPUT**/
StackOverflow.Demos.B
选项 2 :: 获取“容器”类:
/**CODE**/
class Program
{
public static void Main(string[] args)
{
B myClass = new C();
Console.WriteLine(myClass.GetContainerType()); //should output StackOverflow.Demos.B
Console.ReadKey();
}
}
public interface IGetContainerType
{
Type GetContainerType();
}
public class A: IGetContainerType
{
public A() { }
public Type GetContainerType()
{
return typeof(A);
}
}
public class B : A
{
public B() { }
public new Type GetContainerType()
{
return typeof(B);
}
}
public class C : B
{
public C() { }
public new Type GetContainerType()
{
return typeof(C);
}
}
/**OUTPUT**/
StackOverflow.Demos.B
回答相似但不同的问题;获取实例类/完整层次结构:
/**CODE**/
class Program
{
public static void Main(string[] args)
{
C c = new C();
Type myType = c.GetType();
while(myType != null)
{
Console.WriteLine(myType);
myType = myType.BaseType;
}
Console.ReadKey();
}
}
/**OUTPUT**/
StackOverflow.Demos.C
StackOverflow.Demos.B
StackOverflow.Demos.A
System.Object