为什么只有一堂课我的程序运行,而当我有一堂课却不能运行?

时间:2019-01-23 04:23:05

标签: c#

我正在学习如何使用C#编程,并且创建了一个包含两个无效类的程序。该程序将仅运行第一类,而从未执行第二类。

using System;
class Swapper
{
       public void Swap(ref double x, ref double y) 

    {
        double temp = x; //copy x into temp
        x = y; //copy y into x
        y = temp; //copy temp into y (copy the original value of x into y)
    }
    static void Main()
    {
        Swapper switcher = new Swapper();
        var first = 10.5; var second = 10.6;
        Console.Write("first=" + first + "\nsecond=" + second + "\n"); // before swap
        switcher.Swap(ref first, ref second);
        Console.Write("first=" + first + "\nsecond=" + second + "\n"); // after swap

    }
}

class Swapper2
{
    public void Swap2(ref dynamic x2, ref dynamic y2)
    { 
        dynamic temp2 = x2; 
        x2 = y2; 
        y2 = temp2; 
    }

    static void Main2()
    {
        Swapper2 switcher2 = new Swapper2();
        dynamic first2 = 6549744554; dynamic second2 = 10.6M;
        Console.Write("first=" + first2 + "\nsecond=" + second2 + "\n"); 
        switcher2.Swap2(ref first2, ref second2);
        Console.Write("first=" + first2 + "\nsecond=" + second2 + "\n"); 

    }
}

在那之后,我将所有内容放在一个类中,并且确实可以按我的意愿运行:

using System;

class Swapper
{
    public void Swap(ref double x, ref double y) 

    {
        double temp = x; //copy x into temp
        x = y; //copy y into x
        y = temp; //copy temp into y (copy the original value of x into y)
    }

    public void Swap2(ref dynamic x2, ref dynamic y2)

    {
        dynamic temp2 = x2;
        x2 = y2;
        y2 = temp2;
    }

    static void Main()
    {
        Swapper switcher = new Swapper();
        var first = 10.5; var second = 10.6;
        Console.Write("first=" + first + "\nsecond=" + second + "\n"); // before swap
        switcher.Swap(ref first, ref second);
        Console.Write("first=" + first + "\nsecond=" + second + "\n"); // after swap


        Swapper switcher2 = new Swapper();
        dynamic first2 = 6549744554; dynamic second2 = 10.6M;
        Console.Write("first=" + first2 + "\nsecond=" + second2 + "\n");
        switcher2.Swap2(ref first2, ref second2);
        Console.Write("first=" + first2 + "\nsecond=" + second2 + "\n");

    }
}

但是,我不知道发生了什么。 如果代码正确,为什么第一种方法不起作用?为什么在运行第一个类(Swapper)之后停止运行,而没有运行下一个类(Swapper 2)呢?

1 个答案:

答案 0 :(得分:0)

在第一种情况下,代码停止了,因为它完成了Main方法内部的内容,并且由于Main是应用程序Main2的唯一入口点,因此从未执行。您将必须:

  1. Main2 access modifier更改为internalpublic
  2. 然后,由于Main2Swapper2static,因此在Swapper2.Main2()Main的正文中使用Swapper来称呼它们