假如有一个Person类:
public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } public string Title { get; set; } }
执行一个方法:
/// <summary> /// 传递一个泛型委托方法 /// </summary> /// <param name="action"></param> public static void SetNum(Action<Person> action) { Person person = new Person(); //前面的代码 //...... action(person); //后面的代码 //...... }
调用:
static void Main(string[] args) { //第一种写法(写一个方法,然后当参数传进来) SetNum(Set1); //第二种写法(声明一个委托变量,赋一个匿名方法,然后当参数传进来) Action<Person> action = delegate(Person person) { person.Name = "Tom"; }; SetNum(action); //第三种写法(直接new出一个泛型Action,然后赋一个匿名方法,全写) SetNum(new Action<Person>(delegate(Person person) { person.Name = "Name"; })); //第四种写法(直接new出一个匿名方法,简写版) SetNum(delegate(Person person) { person.Name = "Name"; }); } public static void Set1(Person person) { person.Name = "Name"; }
时间: 2024-12-26 01:24:59