C#通用类型继承问题

时间:2011-05-31 07:58:12

标签: c# generics inheritance

class ThirdType : SecondType
{
}

class SecondType : FirstType<SecondType>
{
}

class FirstType<T> 
{
    public static void ShowType()
    {       
        Console.WriteLine(typeof(T).Name);
    }
}


ThirdType.ShowType();

在此代码中,它将打印“SecondType”

我想知道是否可以在这里打印“ThirdType”?

当我调用静态方法ThirdType.ShowType()时,我需要一种方法,它会打印出ThirdType。我能想到的两种方法是将方法修改为

public static void ShowType<O>() 
{ 
  Console.WriteLine(typeof(O).Name);
}

另一种方式是

public static void ShowType(Type t)
{ 
  Console.WriteLine(t.GetType().Name);
}

我想不出任何其他方式

5 个答案:

答案 0 :(得分:3)

没有。为什么要打印ThirdType?您正在打印T的类型,这是您传递给FirstType的通用参数。这是SecondTypeFirstType<SecondType> 如果您要打印ThirdType,则需要将方法更改为:

public void ShowType()
{       
    Console.WriteLine(GetType().Name);
}

并从类的实例中调用它:

ThirdType tt = new ThirdType();
tt.ShowType();

答案 1 :(得分:1)

您可以像这样声明您的ThirdType:

class ThirdType : FirstType<ThirdType>
{
}

class ThirdType : SecondType<ThirdType>
{
}

class SecondType<T> : FirstType<T>
{
}

在这种情况下,它会打印“ThirdType”。但我认为这是不好的做法,我能看到的最佳解决方案在 Daniel 的回答中有所描述

答案 2 :(得分:0)

正如你在代码中写的那样

Console.WriteLine(typeof(T).Name);

和T这里是你在第二类继承中传递的“SecondType”。

打印它的“SecondType”

修改类似这样的代码:可能适合您

class ThirdType : SecondType<ThirdType>
{
}

class SecondType<T> : FirstType<T>
{
}

class FirstType<T> 
{
    public static void ShowType<T>()
    {       
        Console.WriteLine(typeof(T).Name);
    }
}

ThirdType.ShowType();

答案 3 :(得分:0)

你可以做些什么来将泛型抛出窗口,并替换行

Console.WriteLine(typeof(T).Name);

Console.WriteLine(this.GetType().Name);

this.GetType()将返回对象的实际类型,在本例中为ThirdType

从方法中删除static。至少如果你想确保这是有道理的。

答案 4 :(得分:0)

当然,只需添加Console.WriteLine("ThirdType") ;-)

开玩笑 - 当前对象层次结构是不可能的,因为您正在打印泛型类型参数(<T>)的类型,因此将其打印为ThirdType的唯一方法是,如果ThirdType继承自{{ 1}}。