110,536
社区成员
发帖
与我相关
我的任务
分享
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegatesSample
{
class Program
{
static void Main(string[] args)
{
//Predicate , Func , Action 泛型委托
List<string> l = new List<string>();
l.Add("a");
l.Add("b");
l.Add("s");
l.Add("t");
if (l.Exists(s => s.Equals("s")))
{
string str = l.First(s => s.Equals("s"));
Console.WriteLine(str);
//输出 : s
}
else
Console.WriteLine("Not found");
Func<string, bool> p = s => s.Equals("s");
if (l.Exists(p.ToPredicate()))
{
string str = l.First(p);
Console.WriteLine(str);
//输出 : s
}
else
Console.WriteLine("Not found");
string ss = l.First(s =>
{
if (s.Equals("s"))
{
return true;
}
return false;
});
Console.WriteLine(ss);
//输出 : s
List<Entity> entities = new List<Entity>();
entities.Add(new Entity() { Name = "Name1" });
entities.Add(new Entity() { Name = "Name2" });
entities.Add(new Entity() { Name = "Name3" });
entities.Add(new Entity() { Name = "Name4" });
entities.ForEach(item =>
{
Console.WriteLine(item.Name);
//输出 : Name1
//输出 : Name2
//输出 : Name3
//输出 : Name4
});
Queryable(() =>
{
Console.WriteLine(0);
//输出 : 0
});
Queryable((a) =>
{
Console.WriteLine(a);
//输出 : 1
}, 1);
Queryable((a, b) =>
{
Console.WriteLine(a + b);
//输出 : 3
}, 1, 2);
Queryable((a, b, c) =>
{
Console.WriteLine(a + b + c);
//输出 : 6
}, 1, 2, 3);
Queryable((a, b, c, d) =>
{
Console.WriteLine(a + b + c + d);
//输出 : 10
}, 1, 2, 3, 4);
Console.Read();
}
static void Queryable(Action action)
{
action.Invoke();
}
static void Queryable<T>(Action<T> action, T arg1)
{
action.Invoke(arg1);
}
static void Queryable<T1, T2>(Action<T1, T2> action, T1 arg1, T2 arg2)
{
action.Invoke(arg1, arg2);
}
static void Queryable<T1, T2, T3>(Action<T1, T2, T3> action, T1 arg1, T2 arg2, T3 arg3)
{
action.Invoke(arg1, arg2, arg3);
}
static void Queryable<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action, T1 arg1, T2 arg2, T3 arg3, T4 arg4)
{
action.Invoke(arg1, arg2, arg3, arg4);
}
}
public class Entity
{
public string Name { get; set; }
}
public static class Extensions
{
public static Predicate<T> ToPredicate<T>(this Func<T, bool> source)
{
Predicate<T> result = new Predicate<T>(source);
return result;
}
}
}