今天详细了解了返回值reutrn的用法,return语句就是终止它出现在其中的方法的执行,并将控制返回给调用方法。它还可以返回一个可选值。我的理解是:return返回值就是你自己设定的方法运行的结果,这个结果可以用来被其他方法调用。如果方法为Viod类型,则可以省略return语句,如果有其他类型的返回值必需定义相应的返回值类型。一般自定义方法的格式为:
public [访问修饰符] [static] 返回值类型 方法名 (参数)
{
方法体
} //其中[ ]中的内容可写可不写,方法名首字母大写,参数首字母小写。
下面举三个不同的例子:
1、求a和b两数的和。(我们定义两整数和方法,再将和作返回值用来调用)
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入a和b的值:(以回车键隔开)");
int a = int.Parse(Console.ReadLine()); //int.Parse与ToInt32作用一样,将参数值转换为int类型
int b = int.Parse(Console.ReadLine());
int s = Sum(a, b); //调用接收Sum发放中的返回值
Console.WriteLine("两数的和为:"+s);
Console.WriteLine("两数的平均数为:{0}",(double)s/2);
Console.ReadKey();
}
//定义求两整数和方法
public static int Sum(int a, int b) //方法中有返回值,必须定义返回值类型(这里定义的是int),方法中无返回值时返回值类型名一般用Void
{
return a + b;
}
}
2、编辑一个提醒用户是否关机的程序。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("您确定要关机吗?(y/n)");
string s = ReadAnswer(); //调用ReadAnswer方法,并将返回值result赋给s
if (s == "y")
{
Console.WriteLine("正在关机,请稍后!");
}
else
{
Console.WriteLine("请继续使用!");
}
Console.ReadKey();
}
public static String ReadAnswer() //定义一个字符串类型的方法
{
string result = null; //string result=""; //定义字符串型的result并赋初值0,用来接收用户写的内容
do
{
result=Console.ReadLine();
if(result != "y" && result !="n")
{
Console.WriteLine("您输入的内容错误,请重新输入!");
}
} while (result != "y" && result != "n");
return result; //返回string类型的返回值
}
}
3、判断一个年份是平年还是闰年。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("请输入一个年份:");
int year = Convert.ToInt32(Console.ReadLine());
bool result = LeapYear(year);
if (result == true)
{
Console.WriteLine("您好,{0}年是闰年。",year);
}
else
{
Console.WriteLine("您好,{0}年是平年。", year);
}
Console.ReadKey();
}
public static bool LeapYear(int year)
{
if (year % 400 == 0 || year % 4 == 0 && year % 100 != 0)
{
return true;
}
else
{
return false;
}
}
}
注:一个方法只能有一个返回值,且返回的值要与方法中定义的返回值的类型相同。另外,方法可以在同一个类里建,也可以新建类,再在新类里建新方法,调用时:类.方法,如:Console.ReadLine(); Console是类,ReadLine()是方法。