一周学会c#(函数一)
c#才鸟(qq:249178521)
1.前言
· c#不支持全局函数
w 所有的函数必须在类内部声明
· 无源文件和头文件之分
w 所有的函数必须声明的时候被实现
int notallowed() //错误,c#没有全局函数
{
…
}
sealed class methods
{
void inline()
{ …
}
void error()
{ …
}; //错误,函数不能有结尾分号
int alsoerror(); //错误,函数必须声明的时候被实现
}
和java一样,c#不允许有全局函数。所有的函数必须在类或结构内实现。函数是类或结构的成员,函数也被称为方法。
c#允许可以在类的声明中加入结尾分号,例如:
sealed class methods
{
…
};//可以有结尾分号
但是,c#不允许在函数的声明中加入结尾分号,例如:
sealed class methods
{
void notallowed() {…} ; //错误,函数不能有结尾分号
}
2.声明函数
· 函数参数列表
w 各参数以逗号隔开
w 参数必须命名
w 没有参数时括号不能省略
sealed class methods
{
void error(float) //错误,参数没有命名
{ …
}
void noerror(float delta)
{ …
}
int error(void) //错误,无参数时不允许使用void
{ …
}
int noerror()
{ …
}
}
3. 值型参数
· 一般的函数参数是实参的一个拷贝
w 实参必须预先被赋值
w 实参可以是常量类型
sealed class parameterpassing
{
static void method(int parameter)
{
parameter = 42;
}
static void main()
{
int arg = 0;
console.write(arg); //结果为0
method(arg);
console.write(arg); //结果为0
}
}
(注:为了叙述的方便,以后所出现的“参数”这个词均指函数参数,也就是所谓的形参)
没有被ref 或 out修饰的函数参数是一个值型参数。值型参数只有在该参数所属的函数被调用的时候才存在,并且用调用时所传递的实参的值来进行初始化。当函数调用结束时,值型参数不复存在。
只有被预先赋值的实参才能被传递给值型参数,例如:
int arg; // arg没有被赋初值
method(arg);//错误,实参必须预先赋初值
传递给函数的实参可以是纯粹的数而不是变量,例如:
method(42);
method(21 + 21);
