委托作为参数.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace 委托作为参数
{
class 计算器
{
public delegate int delCalculate(int a, int b);
// 将委托作为参数
public void Fun(int a, int b, delCalculate cal)
{
if (cal != null)
{
Console.WriteLine(cal(a,b));
}
}
// 加法
public int Add(int a, int b)
{
return a + b;
}
// 减法
public int Reduce(int a, int b)
{
return a - b;
}
}
class Run
{
static void Main(string[] args)
{
计算器 js = new 计算器();
//调用加法
计算器.delCalculate d1 = new 计算器.delCalculate(js.Add);
js.Fun(20,10, d1); //将委托作为参数
//调用减法
js.Fun(20,10,new 计算器.delCalculate(js.Reduce));
}
}
}
委托调用内部类的方法.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace 委托调用内部类的方法
{
class Person
{
public delegate void myDelegate(string str);
public void Fun(string str)
{
Console.WriteLine(str);
}
//内部类的调用
public class InnerClass
{
public void SubFun(string str)
{
Console.WriteLine(str);
}
}
}
class Program
{
static void Main(string[] args)
{
Person p = new Person();
//内部委托的实例化(用类名调用)
Person.myDelegate pm1 = new Person.myDelegate(p.Fun);
pm1("内部委托调用的方法");
//内部类 InnerClass
Person.InnerClass pc = new Person.InnerClass();
Person.myDelegate pm2 = new Person.myDelegate(pc.SubFun);
pm2("内部委托调用内部类的方法");
}
}
}