WEB开发网
开发学院软件开发C语言 C# 语法练习(8): 函数 阅读

C# 语法练习(8): 函数

 2009-02-23 08:16:55 来源:WEB开发网   
核心提示: 重载: using System;class MyClass{static int Add(int n1, int n2){return n1 + n2;}static string Add(string s1, string s2){return s1 + s2;}static void

重载:

using System;

class MyClass
{
  static int Add(int n1, int n2)
  {
    return n1 + n2;
  }

  static string Add(string s1, string s2)
  {
    return s1 + s2;
  }

  static void Main()
  {
    Console.WriteLine(Add(111,222));   //333
    Console.WriteLine(Add("111", "222")); //111222

    Console.ReadKey();
  }
}

委托(我觉得委托就是把函数当作一种类型的手段):

using System;

class MyClass
{
  delegate double MyFunType(double n1, double n2);

  static double Add(double n1, double n2) { return n1 + n2; }
  static double Dec(double n1, double n2) { return n1 - n2; }
  static double Mul(double n1, double n2) { return n1 * n2; }
  static double Div(double n1, double n2) { return n1 / n2; }

  static void Main()
  {
    MyFunType Fun;

    Fun = new MyFunType(Add); Console.WriteLine(Fun(3, 2)); // 5
    Fun = new MyFunType(Dec); Console.WriteLine(Fun(3, 2)); // 1
    Fun = new MyFunType(Mul); Console.WriteLine(Fun(3, 2)); // 6
    Fun = new MyFunType(Div); Console.WriteLine(Fun(3, 2)); // 1.5

    Console.ReadKey();
  }
}

调用外部函数:

using System;
using System.Runtime.InteropServices;

class MyClass
{
  [DllImport("User32.dll")]
  public static extern int MessageBox(int h, string m, string c, int type);

  static void Main()
  {
    string str = "Visual Studio 2008!";
    MessageBox(0, str, "信息提示", 0);
  }
}

上一页  1 2 3 

Tags:语法 练习 函数

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接