开发者

C# Generic Type Inheritance Question

class ThirdType : SecondType
{
}

class SecondType : FirstType<SecondType>
{
}

class FirstType<T> 
{
    public static void ShowType()
    {       
        Console.Write开发者_JAVA百科Line(typeof(T).Name);
    }
}


ThirdType.ShowType();

In this code, it will print "SecondType"

I want to know if it is possible to print "ThirdType" here?

I need a way when I call the static method ThirdType.ShowType(), it will print out ThirdType. Two ways I can think of is to modify the method to

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

another way is

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

I can't think of any other ways


No. Why should it print ThirdType? You are printing the type of T which is the generic parameter you passed to FirstType. And this is SecondType: FirstType<SecondType> If you want to print ThirdType you need to change your method to this:

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

and call it from an instance of the class:

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


You can declare your ThirdType like this:

class ThirdType : FirstType<ThirdType>
{
}

or

class ThirdType : SecondType<ThirdType>
{
}

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

In this case it would print "ThirdType". But I thinks this would be bad practice, the best solution I can see is described in Daniel's answer


What you can do it to throw the generics out the window, and replace the line

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

with

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

this.GetType() will return the actual type of the object, in this case ThirdType.

And remove staticfrom the method. At least if you want to make sure this makes any sense.


Sure, just add Console.WriteLine("ThirdType") ;-)

Just kidding - no it is not possible with your current object hierarchy because you are printing the type of the generic type argument (<T>) so the only way to have it print ThirdType is if ThirdType inherited from FirstType<ThirdType>.


As You have written in you code

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

and T here is "SecondType" which you passed in second class inheriatance .

thants y its printing "SecondType"

Modify you code something like this : may work for you

class ThirdType : SecondType<ThirdType>
{
}

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

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

ThirdType.ShowType();

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜