一:方法
}
namespace 工资交税
{ class Program
{
static void Main(string[] args)
{
double s, s2;
Console.Write("税前工资:");
s = double.Parse(Console.ReadLine()); s2 = getTax(s);
Console.WriteLine("税后工资{0}:", s - s2);
Console.Write("按回车结束");
Console.ReadLine();
}
private static double getTax(double s)
{
if (s <= 5000)
return 0;
return (s - 5000) * 0.1;
}
}
}
运行结果:
列二:实现交换两个数的方法swap()
namespace ch06
{
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
Console.WriteLine("交换前:x={0},y={1}", x, y);
swap(x, y);
Console.WriteLine("交换后:x={0},y={1}", x, y);
Console.Write("按回车结束!");
Console.ReadLine();
}
private static void swap(int a, int b)
{
int t;
t = a;
a = b;
b = t;
}
}
}
运行结果如下:
其实这在c语言中早已学过,这位值传递,不会真的交换两个数的值
原理图用老师画的这个吧:
只是相当于起啦个别名!
(2)按引用传递方法参数,相当于传地址
namespace ch06 { class Program { static void Main(string[] args) { int x = 10, y = 20; Console.WriteLine("交换前:x={0},y={1}", x, y); swap(ref x,ref y); Console.WriteLine("交换后:x={0},y={1}", x, y); Console.Write("按回车结束!"); Console.ReadLine(); } private static void swap(ref int a,ref int b) { int t; t = a; a = b; b = t; } } }
三:值类型和引用类型
namespace ch031
{
class Program
{
static void Main(string[] args)
{
Student s1,s2;
s1 = new Student();
s1.age = 10;
s2 = s1;//相当于赋值,即int a,b ;a=b;
s2.age = 20;
Console.WriteLine(s1.age);//什么结果
Console.WriteLine(s2.age);
Console.ReadLine();
}
class Student
{
public int age;
}
}
}
namespace ch031
{
class Program
{
static void Main(string[] args)
{
Student s1,s2;
s1 = new Student();
s1.age = 10;
s2 = s1;
s2 = new Student();
s2.age = 20;
Console.WriteLine(s1.age);//什么结果
Console.WriteLine(s2.age);
Console.ReadLine();
}
class Student
{
public int age;
}
}
}