目录
例1:
namespace ConsoleApp9
{
class Program
{
static void Main(string[] args)
{
Dictionary<char, Func<float, float, float>> myDictionary = new Dictionary<char, Func<float, float, float>>();
myDictionary.Add('+', Add);
myDictionary.Add('-', Substract);
myDictionary.Add('*', Multiply);
myDictionary.Add('/', Divide);
myDictionary['+'](9, 3);
myDictionary['-'](9, 3);
myDictionary['*'](9, 3);
myDictionary['/'](9, 3);
Console.ReadKey();
}
public static float Add(float a, float b)
{
float result = a + b;
Console.WriteLine(a + "+" + b + "的值为:" + result);
return result ;
}
public static float Substract(float a, float b)
{
float result = a - b;
Console.WriteLine(a + "-" + b + "的值为:" + result);
return result;
}
public static float Multiply(float a, float b)
{
float result = a * b;
Console.WriteLine(a + "*" + b + "的值为:" + result);
return result;
}
public static float Divide(float a, float b)
{
float result = a / b;
Console.WriteLine(a + "/" + b + "的值为:" + result);
return result;
}
}
}
例2:
class Program
{
static void Main(string[] args)
{
Dictionary<string, Action<string>> myDictionary = new Dictionary<string, Action<string>>();
if(!myDictionary.ContainsKey ("姓名"))
{
myDictionary["姓名"] = null;
}
myDictionary["姓名"] += Test1;
myDictionary["姓名"] += Test2;
myDictionary["姓名"] += Test3;
myDictionary["姓名"]("李疆");
Console.ReadKey();
}
public static void Test1(string name)
{
Console.WriteLine("你好,"+name );
}
public static void Test2(string name)
{
Console.WriteLine("很高兴认识你,"+name );
}
public static void Test3(string name)
{
Console.WriteLine("拜拜,"+name );
}
}