c#中的方法的定义和运用

首先,理解下,函数和方法:

其实两者是一样的,只是个叫法不同。

C#中叫做Method,中文叫方法;

C++中称为Function,中文叫函数。

函数Function,多指以前面向过程编程时候,将逻辑编写为一个一个过程,称之为函数。

方法Method,是发展为面向对象的时候,代码以类的方式来组织,类的里面是成员变量和成员函数,对应地也叫做数据和方法(method)。

下面代码是简单测试调用方法,这个方法用来判断一个数是否是素数。

 1  1     using System;  
 2  2     using System.Collections.Generic;  
 3  3     using System.Linq;  
 4  4     using System.Text;  
 5  5       
 6  6     namespace main  
 7  7     {  
 8  8         //共同的命名空间中定义Program类,类中定义一个静态方法(函数)Judge1和主函数Main函数。  
 9  9         class Program  
10 10         {  
11 11       
12 12             public static bool Judge1(int num)  
13 13             {  
14 14                 int i;  
15 15       
16 16                 for (i = 2; i < num; i++)  
17 17                 {  
18 18                     if (num % i == 0)  
19 19                     {  
20 20                         break;  
21 21                     }  
22 22                 }  
23 23       
24 24                 if (i == num)  
25 25                 {  
26 26                     return true;  
27 27                 }  
28 28                 else  
29 29                 {  
30 30                     return false;  
31 31                 }  
32 32             }  
33 33       
34 34             //主函数中调用Judgeclass类中的方法(函数)  
35 35             static void Main(string[] args)  
36 36             {  
37 37                 Console.WriteLine("输入一个整数");  
38 38                 int i = int.Parse(Console.ReadLine());  
39 39                 Judgeclass.showisSushu(i);  
40 40       
41 41             }  
42 42         }  
43 43     } 
View Code

 

另外的一个类,这个类中有一个静态方法:

 1 1 using System;  
 2  2 using System.Collections.Generic;  
 3  3 using System.Linq;  
 4  4 using System.Text;  
 5  5   
 6  6 namespace main  
 7  7 {  
 8  8     //在同一个命名空间中添加类,然后在类中定义方法(函数),在这个函数中调用另外一个类中的方法。  
 9  9     class Judgeclass  
10 10     {  
11 11         public static void showisSushu(int a)  
12 12         {  
13 13             if (Program.Judge1(a))  
14 14             {  
15 15                 Console.WriteLine("{0}是素数", a);  
16 16             }  
17 17             else  
18 18             {  
19 19                 Console.WriteLine("{0}不是素数", a);  
20 20             }  
21 21         }  
22 22     }  
23 23 }  
View Code

 

转载于:https://www.cnblogs.com/zcwvictor-2012/p/3720818.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值