[Day16]C# 鸡础观念- 虚拟代工厂~方法(function)

人类的世界有许多的工厂,
将原料送入後就会变成商品,
C#的世界里也是,
方法就像一间间的工厂一样,
一发包就能得到想要的东西

方法(function)

  • 为了解决以下问题:
    1.程序码的重复
    2.结构很不清晰
    3.有利於修改与维护
  • 他就像是一间代工厂一样

https://ithelp.ithome.com.tw/upload/images/20210916/20097001aX9kdraTMz.png

字串方法/images/emoticon/emoticon29.gif

  • 会回传处理後的字串
  • 可以自己定义传入的参数

范例:我们来回传孤独一只鸡的字串

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpDemo
{

    class Program
    {
        static void Main(string[] args)
        {
            //我们来呼叫方法并赋值给变数
            string animal = GetChicken();
            Console.WriteLine(animal);
            Console.ReadKey();
        }
        //宣告字串方法
        static string GetChicken()
        {
            return "孤独一只鸡";
        }
    }
  }

结果:

孤独一只鸡

使用static关键字时,表示他是静态的,所以不需要去new他
https://ithelp.ithome.com.tw/upload/images/20210917/200970012uV77UtFx6.png

范例:我们抛今天的日期到方法中,让他自动组成年月日

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CsharpDemo
{

    class Program
    {
        static void Main(string[] args)
        {
            //来取得过去的一个时间吧
            string MtDate = GetDate(1995, 4, 9);
            Console.WriteLine(MtDate);

            //来取得今日的时间吧
            MtDate = GetDate(2021, 9, 17);
            Console.WriteLine(MtDate);
            Console.ReadKey();
        }
        //宣告一个组合日期的方法
        static string GetDate(int y,int M,int d)
        {
            //因为值传进来是正数所以需要转成字串
            string Date_y = Convert.ToString(y);//第一种转型方式Convert.To...
            string Date_M = M.ToString();//第二种转型方式 参数.ToString()
            string Date_d = d.ToString();

            //组合回传字串,用return回传
            return Date_y + "年 " + Date_M + "月 " + Date_d + "日";
        }

    }
  }

结果:

1995年 4月 9日
2021年 9月 17日

有了方法,可以大大降低程序码的重复率,也可以随处呼叫他


<<:  OVN 介绍

>>:  企划实现(2)

在 ubuntu 21.04 上轻松安装呒虾米

本文同步刊载於我的部落格:在 ubuntu 21.04 上轻松安装呒虾米 来试试在 ubuntu 2...

day14 : 前半段小结

参赛将近半个月,终於完成了我认为贴近infra的部分,这也是为什麽要做个小结的原因,大部分企业在使用...

【Day 22】Hook 05:useReducer

Reducer Reducer 这个概念, 来源於 React 的延伸套件 Redux, 其核心由 ...

【Day27】this - 简易呼叫(Simple Call)

简易呼叫(Simple Call) 当我们直接执行函式时,就是所谓的简易呼叫(Simple Call...