一:方法
C#中的方法与其他面向对象语言中的方法含义相同
定义方法的语法
访问修饰符 返回类型 方法名 ( 参数列表 )
{
// 方法体…
}
例1:计算税后工资
工资计税的方法为:低于等于5000不计税,超出5000的部分按10%缴税
定义getTax的方法:实现计算税后工资
private double getTax(double income)
{
}
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语言中早已学过,这位值传递,不会真的交换两个数的值
调用方法时,默认情况下使用按值传递的方式进行传参。
与C语言中传递值、传递指针类似。
按值传递,传递的是参数的值。调用方法中的变量与被调用方法的实参是2个不同的变量,具有不同内存地址。两者的改变互不影响。
原理图用老师画的这个吧:
只是相当于起啦个别名!
(2)按引用传递方法参数,相当于传地址
在参数前面添加ref关键字,则按照引用方式传递参数。
在定义方法和调用方法时,都要添加ref关键字。
类似于C语言的传递指针(地址)。
例:使用按引用传参方式来交互2数。
void swap(ref int a, ref int b)
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;
}
}
}
运行图:如下
三:值类型和引用类型
C#中变量可分为值类型与引用类型两类。
由类创建的对象都是引用类型。
class Student{…}
Student s=newStudent();
String、数组也是引用类型。
简单类型(数值、日期、布尔)和结构体是值类型。
例一:
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;
}
}
}
运行图:
原理图: