标签:c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static int val;
//函数
//1. 关键字static:静态函数,void:无返回值,return:程序立即返回调用代码;
//实例1: 函数参数
static double product(double param1, double param2)
{
return param1 * param2;
}
//实例2: 参数数组
static int Add(params int[] p)
{
int sum = 0;
foreach (int i in p)
sum += i;
return sum;
}
//实例3: 值传递函数,结果不改变
static void ShowDoulbe(int val)
{
val *= 2;
Console.WriteLine("val doubled ={0}", val);
}
//实例4: 无参函数,结果改变
static void ShowDoulbe()
{
val *= 2;
Console.WriteLine("val doubled ={0}", val);
}
//实例5: 引用传递函数,结果改变
static void ShowDoulbe(ref int val)
{
val *= 2;
Console.WriteLine("val doubled ={0}", val);
}
//实例6: 输出函数
static void outfun(out string str)
{
str = "test";
str += "fun";
Console.WriteLine("outfun result: {0}", str);
}
static void Main(string[] args)
{
//调用函数参数
Console.WriteLine("Call func parameter;");
double a = product(1.2, 2.1);
Console.WriteLine(a);
//调用参数数组
Console.WriteLine("Call parameter array;");
int sum = Add(1, 3, 5, 7);
Console.WriteLine(sum);
//调用无参函数,结果改变
Console.WriteLine("Call non-parameter func;");
val = 5;
Console.WriteLine("Befor the call;");
Console.WriteLine("myNumber={0}", val);
Console.WriteLine("After the call;");
ShowDoulbe();
Console.WriteLine("myNumber={0}", val);
//调用值传递函数,结果不改变
Console.WriteLine("Call value-passed func;");
int myNumber = 5;
Console.WriteLine("Befor the call;");
Console.WriteLine("myNumber={0}", myNumber);
Console.WriteLine("After the call;");
ShowDoulbe(myNumber);
Console.WriteLine("myNumber={0}", myNumber);
//调用引用传递函数,结果改变
Console.WriteLine("Call reference-passed func;");
int myNumber2 = 5;
Console.WriteLine("Befor the call;");
Console.WriteLine("myNumber={0}", myNumber2);
Console.WriteLine("After the call;");
ShowDoulbe(ref myNumber2);
Console.WriteLine("myNumber={0}", myNumber2);
//调用输出函数
Console.WriteLine("Call out parameter function;");
string test2;
outfun(out test2);
Console.ReadLine();
}
}
}
本文出自 “Ricky's Blog” 博客,请务必保留此出处http://57388.blog.51cto.com/47388/1650866
10.C# -- 函数参数,参数数组,值传递函数,引用传递函数,输出函数,无参函数
标签:c#
原文地址:http://57388.blog.51cto.com/47388/1650866