.NET中常见概念的简单易用教程
委托是对函数的抽象
语法:delegate 函数体
class A
{
//委托定义
public delegate void UpdateListView_Delegate(int rowIndex);
}
事件是一种限制性的委托,依赖于委托
语法:event 委托名 事件名;
事件机制:当事件被触发时,将会根据链接顺序依次执行
class A
{
//事件定义
public event UpdateListView_Delegate eventUpdateListView;
//触发事件
if(eventUpdateListView != null)
eventUpdateListView(1);
}
//别的类中链接并处理事件
class B
{
A a = new A();
void Load()
{
a.eventUpdateListView += 接收事件函数;
}
public void 接收事件函数(int rowIndex)
{
//事件处理
}
}
lamdba允许在函数体内编写一个匿名函数
语法:委托 = (不带参数类型的参数名列表) => { };
(=> 读作 goes to)
使用lamdba简写class B
class B
{
A a = new A();
void Load()
{
a.eventUpdateListView += (rowIndex) =>
{
//事件处理
};
}
}
invoke:在非主线程或非本进程中执行修改ui的同步方法
beginInvoke:修改ui的异步方法
语法:执行者.Invoke(委托实例, 参数列表数组);
执行者必须为【本进程的主线程】的拥有窗体句柄的控件(简单来说就是ui控件,如form、button等)
public delegate void UpdateListView_Delegate(int rowIndex);
//此方法可在线程中调用
public void UpdateListView_Invoke(int rowIndex)
{
//this.Invoke(委托实例, 参数);
UpdateListView_Delegate instance = new UpdateListView_Delegate(UpdateListView);
this.Invoke(instance, new object[]{rowIndex});
}
//一个普通的修改ui的函数,无需过多关注
public void UpdateListView(int rowIndex)
{
listView1.Items[rowIndex].SubItems[6].Text = "更改文字";
listView1.Update();
}
lamdba简化上诉代码
public delegate void UpdateListView_Delegate(int rowIndex);
//此方法可在线程中调用
public void UpdateListView_Invoke(int rowIndex)
{
UpdateInstructListView_Delegate instance = (_rowIndex) =>
{
listView_cutInstruct.Items[_rowIndex].SubItems[6].Text = "更改文字";
listView_cutInstruct.Update();
};
this.Invoke(instance, new object[]{rowIndex});
}
.NET的System命名空间提供了默认无返回委托 Action<>,和有返回的委托<T> Func<>,绝大部分情况都够用了
public delegate void Action();
public delegate void Action<T>(T obj);
public delegate void Action<T1, T2>(T1 arg1, T2 arg2);
public delegate void Action<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3);
public delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
public delegate TResult Func<TResult>();
public delegate TResult Func<T, TResult>(T arg);
public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);
public delegate TResult Func<T1, T2, T3, TResult>(T1 arg1, T2 arg2, T3 arg3);
public delegate TResult Func<T1, T2, T3, T4, TResult>(T1 arg1, T2 arg2, T3 arg3, T4 arg4);
使用Action<>继续简化上述Invoke示例代码
//此方法可在线程中调用
public void UpdateListView_Invoke(int rowIndex)
{
Action<int> instance = (_rowIndex) =>
{
listView_cutInstruct.Items[_rowIndex].SubItems[6].Text = "更改文字";
listView_cutInstruct.Update();
};
this.Invoke(instance, new object[]{rowIndex});
}
以上为实际开发中较为常见的代码,已较为简洁。