我正在学习如何使用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)呢?
答案 0 :(得分:0)
在第一种情况下,代码停止了,因为它完成了Main
方法内部的内容,并且由于Main
是应用程序Main2
的唯一入口点,因此从未执行。您将必须:
Main2
access modifier更改为internal
或public
Main2
和Swapper2
是static,因此在Swapper2.Main2()
中Main
的正文中使用Swapper
来称呼它们