tanl

为了弄清这个代码,写了个测试,但是测试的结果和往上的代码有所差别,仁者见仁,智者见智了。如果我的测试用例用问题,欢迎指出。

首先,方法的是在被调用时执行,但是静态方法在所有地方都可以调用,应该在很早的时候就被编译了。这个测试依赖静态方法来输出顺序。

    public class WhenCodeThread : ITestSample
    {
        public class Test : TestBase
        {
             int instanceParam2 = staticFunction("子类实体变量");
             static int staticParam2 = staticFunction("子类静态变量");
            static Test()
            {
                Console.WriteLine("-- 子类静态构造函数被执行 --");
            }

            public Test()
            {
                Console.WriteLine("-- 子类实体构造函数被执行 --");
            }
        }
        public class TestBase
        {
            int instanceParam = staticFunction("基类实体变量");
            static int staticParam = staticFunction("基类静态变量");
            static TestBase()
            {
                Console.WriteLine("-- 基类静态构造函数被执行 --");
            }

            public TestBase()
            {
                Console.WriteLine("-- 基类实体构造函数被执行 --");
            }

            protected static int staticFunction(string name)
            {
                Console.WriteLine($"-- {name}被执行 --");
                return 1;
            }

        }

        public event Action TestCompleted;
        public void StartTest()
        {
            Console.WriteLine("-- 第一次实例化类 --");
            new Test();

            Console.WriteLine("-- 第二次实例化类 --");
            new Test();
        }

    }

控制台调用 StartTest() 可以看到结果

 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-04-12
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-03
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-01-29
  • 2022-01-07
  • 2021-12-23
  • 2022-12-23
相关资源
相似解决方案