using System;
namespace Athrun
{
class Method
{
public static void MyMethod()
{
Console.WriteLine("this is a method");
}
static void Main()
{
MyMethod();
}
}
}
Code
//有返回值的方法
using System;
namespace Athrun
{
class Method
{
public static DateTime MyMethod()
{
return DateTime.Now;
}
static void Main()
{
Console.WriteLine("Now time is {0}",MyMethod());
}
}
}
Code
//带参数的方法
using System;
namespace Athrun
{
class Method
{
public static void MyMethod(string aName)
{
Console.WriteLine("this Name is " + aName + "\n");
}
static void Main()
{
string s=" 带参数的方法";
MyMethod(s);
}
}
}
//带参数的方法
using System;
namespace Athrun
{
class Method
{
public static void MyMethod(string aName)
{
Console.WriteLine("this Name is " + aName + "\n");
}
static void Main()
{
string TempName="";
while (TempName!="end")
{
TempName=Console.ReadLine();
MyMethod(TempName);
}
}
}
}
//带参数的方法
using System;
namespace Athrun
{
class Method
{
public static int add(int i,int j)
{
return i+j;
}
static void Main()
{
int i=5;
int j=3;
Console.WriteLine("i+j=" + add(i,j));
}
}
}
![](https://kb.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
using System;
namespace Athrun
{
class Method
{
class A
{
//类中的静态成员变量在各个实例中是共享的
public static int i=0;
public void addi()
{
i=i+1;
}
}
static void Main()
{
A a=new A();
a.addi();
A b=new A();
b.addi();
Console.WriteLine(A.i);
}
}
}
/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2008/8/26
* Time: 下午 07:35
*
* To change this template use Tools | Options | Coding | Edit Standard Headers.
*/
// 方法的参数传递有三个不同的方式:值传递,引用传递,输出参数传递
/* 引用传参和输出参数都是以引用类型来传递其地址的,这两者唯一不同的是
* 用输出参数时必需在方法内对数进行初始化,而引用方式时必须在调用外
* 对参数进行初始化。
* */
using System;
class Method
{
//值传递方式
public static void ValueMethod(int i)
{
i++;
}
//引用传参方式
public static void RefMethod(ref int i)
{
i++;
}
//带输出参数的方法
public static void OutMethod(out int i)
{
i=0;
i++;
}
static void Main()
{
int i=0;
ValueMethod(i);
Console.WriteLine("i={0}",i);
int j=0;
RefMethod(ref j);
Console.WriteLine("j={0}",j);
int k;
OutMethod(out k);
Console.WriteLine("k={0}",k);
}
}
Code
/*
* Created by SharpDevelop.
* User: Administrator
* Date: 2008/8/26
* Time: 下午 07:47
* 可变数量参数的方法
* 值类型 引用类型
* 变量中存放 真正的数据 指向数据的指针
* 內存空间分配 堆栈(stack) 托管堆中(managed heap)
* 內存需求 一般来說很少 较大
* 执行效能 较快 较慢
* 內存释放时间 执行超过定义变量的作用域 由回收站负责回收
* 可以为null 不可以 可以
* 特定条件中值类型需要进行裝箱和拆箱的操作这样会影响它的性能。
* 字符串也是一個引用类型的,但字符串有所不同,字符串是一個新对象。
* 新对象最大的一個特点就是它是不可变的
*
*
*/
using System;
class Method
{
static void setstr(string s)
{
s="123456789";
}
static int addi(params int[] values)
{
int sum=0;
foreach (int i in values)
sum+=i;
return sum;
}
//数组是引用类型
static void printarr(int[] arr)
{
for(int i=0;i<arr.Length;i++)
arr[i]=i;
}
static void Main()
{
// int[] arr=new int[]{100,200,300,400,500,600,700,800,900,1000};
// printarr(arr);
// foreach (int i in arr)
// Console.WriteLine(i+", ");
//Console.WriteLine(addi(a));
string s="3333";
setstr(s);
Console.WriteLine(s);
}
}