C#,入门教程(22)——函数的基础知识

上一篇:

C#,入门教程(21)------命名空间(namespace)与程序结构的基础知识https://blog.csdn.net/beijinghorn/article/details/124140653

一、函数的基本概念

一个软件的结构大体如下:

大厦application: a plaza

{

----有若干层namespace: have some levels

----{

--------每一层有若干房间class: level have some rooms

--------{

------------房间有一些东西attributes: rooms have some things

------------房间里面可以用这些东西搞一些事情functions: and can do somethings with somethings.

--------}

----}

}

函数与属性都是结构体、类的组成部分。

属性(字段)用于保存数据。

函数就是用数据处理,并得到一些记过的功能性程序模块。

函数既可以处理本类/结构体的数据,也可以处理外部的其他数据。

cs 复制代码
public class className
{
    public int AttName { get; set;} = 0;

    public string OutputAtt()
    {
        return String.Format("{0:D8}", AttName);
    }
}

二、函数的不同应用场景

1、有些函数"只进不出"

cs 复制代码
public void Step()
{
    Att += 1;
}

2、有些函数"只出不进"

cs 复制代码
public string Print()
{
    return String.Format("{0:D8}", Att);
}

3、有些函数"又进又出"

cs 复制代码
public string PrintD8(int a)
{
    return String.Format("{0:D8}", a);
}

a 称为"参数"。参数可以很多,用逗号分开即可。

cs 复制代码
public int Sum(int a, int b)
{
    return (a + b);
}

4、更复杂的数据

cs 复制代码
public int Sum(int[] a)
{
    int sum = 0;
    for(int i=0; i<a.Length; i++)
    {
        sum += a[i];
    }
    return sum;
}

5、怎么得到多个计算结果?

cs 复制代码
public int[] Sum(int[] a)
{
    int sum = 0;
    int max = int.MinValue;
    int min = int.MaxValue;
    for(int i=0; i<a.Length; i++)
    {
        sum += a[i];
        if(a[i] < min) min = a[i];
        if(a[i] > max) max = a[i];
    }
    return new int[3] { min, max, sum };
}

6、如果多个返回值类型不统一,怎么办?

cs 复制代码
public double Mean(int[] a, out int min, out int max, out int sum)
{
    sum = 0;
    max = int.MinValue;
    min = int.MaxValue;
    for(int i=0; i<a.Length; i++)
    {
        sum += a[i];
        if(a[i] < min) min = a[i];
        if(a[i] > max) max = a[i];
    }
    return ((double)sum / a.Length);
}

7、修改参数的数据?

一般而言,参数仅仅作为原始数据传入函数,不能修改参数的数据。

需要一点点技术的定义。

cs 复制代码
public void MoveTo(ref int[] p, double rad, double angle)
{
    p[0] += rad * Math.Cos(angle * Math.PI / 180.0);
    p[1] += rad * Math.Sin(angle * Math.PI / 180.0);
}

三、关于函数的高级知识

1、重载 override 与 重写 new

2、委托 delegate 与 接口 interface

3、递归方法 Recurse Method

这些知识是后面会逐个讲解的,先列出目录。

四、关于函数的更多要点

1、每个函数不要写太多行!

2、只要是可能重复的,都写成函数(模块化!)

3、追求功能而不是性能的前提下,可用传入参数,而不是直接使用属性;

4、函数的名字要用全称的英语单词,不要简写或莫名其妙的,比如 AA BB WC。

下一篇:

C#,入门教程(23)------数据类型转换的一点基础知识https://blog.csdn.net/beijinghorn/article/details/124187182

相关推荐
来恩10031 小时前
C# 类与对象详解
开发语言·c#
Dr.勿忘4 小时前
C#面试常考随笔8:using关键字有哪些用法?
开发语言·unity·面试·c#·游戏引擎
xcLeigh4 小时前
WPF进阶 | WPF 数据绑定进阶:绑定模式、转换器与验证
c#·wpf
谢大旭5 小时前
ASP.NET Core 中间件
后端·中间件·c#
时光追逐者5 小时前
Visual Studio使用GitHub Copilot提高.NET开发工作效率
c#·github·.net·copilot·ai编程·微软技术·visual studio
唐青枫7 小时前
dotnet LINQ 使用简明教程
c#·.net
谢大旭8 小时前
.Net Web API 访问权限限定
开发语言·c#
幻想趾于现实10 小时前
如何用函数去计算x年x月x日是(C#)
开发语言·c#
我命由我123451 天前
游戏引擎 Unity - Unity 下载与安装
c语言·开发语言·c++·后端·unity·c#·游戏引擎
我命由我123451 天前
游戏引擎 Unity - Unity 启动(下载 Unity Editor、生成 Unity Personal Edition 许可证)
c语言·c++·后端·unity·c#·游戏引擎·ue4