Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c# - Why does this code replace float with long?

I have this code as an example:

class A<T> {
    public class B : A<long> {
        public void f() {
            Console.WriteLine( typeof(T).ToString());
        }
 
    public class C : A<long>.B { }
    
    } 
}

class Prg5 { static void Main() {
    var c = new A<float>.B.C();
    c.f();
} }

With output:

System.Int64

Why does it print the type for long? How and where does the float type passed originally get replaced?

question from:https://stackoverflow.com/questions/65952881/why-does-this-code-replace-float-with-long

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The type C is defined as:

public class C : A<long>.B { }

The type A is defined as:

class A<T> {
    public class B : A<long> {
        public void f() {
            Console.WriteLine( typeof(T).ToString());
        }    

    public class C : A<long>.B { }
    } 
}

So if you create a new C then the type parameter for A is long.

In the statement var c = new A<float>.B.C();, A<float> and B are just parts of the "path" to the nested class C. The fact that A<float> is part of that path does not change the fact that C is an A<long>.B.

The float parameter and the fact that B is an A<long> are not relevant to determine the type of T inside c.f().


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...