首页 > 解决方案 > 为什么这段代码用long替换float?

问题描述

我以这段代码为例:

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();
} }

带输出:

System.Int64

为什么它会长时间打印类型?最初传递的浮点类型是如何以及在哪里被替换的?

标签: c#genericstypesinstanceinner-classes

解决方案


类型C定义为:

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

类型A定义为:

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

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

因此,如果您创建一个新C的,则类型参数Along

在语句中var c = new A<float>.B.C();A<float>B只是嵌套类的“路径”的一部分C。作为该路径的一部分的事实A<float>不会改变.CA<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().


推荐阅读