方法(函数)
[public] static 返回值类型 方法名([参数列表])
{
方法体;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChuangzhiConsel
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("第一个整数:");
int n1 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("第二个整数:");
int n2 = Convert.ToInt32(Console.ReadLine());
int max_value = Program.GetMax(n1, n2);
Console.WriteLine("最大值为:{0}", max_value);
Console.ReadKey();
}
/// <summary>
/// 求最大值
/// </summary>
/// <param name="n1"></param>
/// <param name="n2"></param>
/// <returns></returns>
public static int GetMax(int n1, int n2)
{
return n1 > n2 ? n1 : n2;
}
}
}
调用问题
先写类再方法名,调用者用到被调用者的值:
1、传参,推荐
2、使用静态字段来模拟全局变量,c#没有声明全局变量,是使用static
class Program
{
public static int _NUMBER = 10;//字段
static void Main(string[] args)
{
形参与实参都在内存中开辟空间。
方法功能注意事项
方法的功能要单一,最忌讳出现提示用户输入的字眼,正确:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChuangzhiConsel
{
class Program
{
public static int _NUMBER = 10;
static void Main(string[] args)
{
Console.WriteLine("请输入一个数字:");
string input = Console.ReadLine();
int n = Program.GetNumber(input);
Console.WriteLine("接收了:{0}", n);
Console.ReadKey();
}
public static int GetNumber(string s)
{
while (true)
{
try
{
int number = Convert.ToInt32(s);
return number;
}
catch
{
Console.WriteLine("输入错误!!!");
s = Console.ReadLine();
}
}
}
}
}
调用方法判断质数
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChuangzhiConsel
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("\t\t输入数字判断是否是质数");
while (true)
{
Console.WriteLine("请输入一个数字:");
string s = Console.ReadLine();
int n = Transform_Int(s);
bool isPrime = Is_Prime(n);
if (isPrime)
{
Console.WriteLine("是质数哦!");
}
else
{
Console.WriteLine("不是质数唉!");
}
}
}
public static int Transform_Int(string str)
{
while (true)
{
try
{
int number = Convert.ToInt32(str);
return number;
}
catch
{
Console.WriteLine("输入的不是数字,请重新输入:");
str = Console.ReadLine();
}
}
}
public static bool Is_Prime(int nums)
{
if (nums < 2)
{
if (nums == 1)
{
return true;
}
return false;
}
else
{
for (int i = 2; i < nums; i++)//2<2不成立
{
if (nums % i == 0)
{
return false;//不是质数
}
}
return true;//是质数
}
}
}
}