/// <summary> /// 调用委托的类 /// </summary> public static void DelegateFun() { //声明一个委托 MyAction ac1 = Fun2; ac1("ac1");//调用委托 DelegateTest test = new DelegateTest(); MyAction ac_fun1 = test.Fun1; ac_fun1.Invoke("hello world");//Invoke方法也可以调用委托 return; //匿名委托 MyAction2 ac2 = delegate(string str) { Console.WriteLine(str); return(1); }; ac2("ac2"); //使用lambda表达式 MyAction2 ac3 = str => 1; Console.WriteLine(ac3("ac3")); // 使用泛型委托 // Action是无返回值的泛型委托。它也是用:public delegate void Action<in T>(T obj);声明得到的 // Action至少0个参数,至多16个参数,无返回值。 Action <int, int> ac4 = (str, str2) => Console.WriteLine(str + str2); ac4(1, 2); // Func是有返回值的泛型委托。它是用:public delegate TResult Func<in T, out TResult>(T arg);声明得到的 // Func至少0个参数,至多16个参数,根据返回值泛型返回。必须有返回值,不可void Func <int, int, bool> ac5 = (str, str2) => { if (str > str2) { return(true); } else { return(false); } }; Console.WriteLine(ac5(5, 3)); //myCase: Predicate <int> ac6 = (str) => { return(str % 2 == 0 ? true : false); }; Console.WriteLine(ac6(0)); }
public static dynamic Func <T>(MyAction2 <T> myAction, ref ErrorInfo err, ApiRequesSaveEntityBean <T> inEnt) { try { return(myAction(ref err, inEnt)); } catch (Exception e) { err.IsError = true; err.Message = e.Message; return(err); } }
public void InvokeAll() { MyEvent1(this, EventArgs.Empty); MyEvent2.Invoke(this, EventArgs.Empty); MyEvent3.DynamicInvoke(this, EventArgs.Empty); MyEvent4.BeginInvoke(this, EventArgs.Empty, null, null); this.MyEvent5(this, EventArgs.Empty); MyEvent6?.Invoke(this, EventArgs.Empty); MyAction1(this, EventArgs.Empty); MyAction2.Invoke(this, EventArgs.Empty); MyAction3.DynamicInvoke(this, EventArgs.Empty); MyAction4.BeginInvoke(this, EventArgs.Empty, null, null); this.MyAction5(this, EventArgs.Empty); MyAction6?.Invoke(this, EventArgs.Empty); }