委托入门案例

C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针。委托(Delegate) 是存有对某个方法的引用的一种引用类型变量。引用可在运行时被改变。

对于委托最多的使用就是子线程调用主线程的控件的使用。可能使用winform或者wpf的人接触的多一点。

这里最主要还是给大家看看委托的案例吧

delegate void showMsg(string Msg);
showMsg s;

第一种委托的方法
s=func;
s("aaa");


第二种委托方法
s=new showMsg(func);
s("aaa")'

public static void func(string s)
{
console.WriteLine("aaa"+s);
}

当然也有 这种方式的委托,在应用程序的主线程上执行指定的委托

this.Invoke(new Action(()=>{Console.WriterLine("aaa")}); 

  委托开启线程去执行
this.Dispatcher.BeginInvoke((Action)delegate ()
                {Console.WriterLine("aaa")});
 
 
 public event PropertyChangedEventHandler PropertyChanged;

private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
  handler(this, new PropertyChangedEventArgs(propertyName));
}
}

// 简化委托

  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
 
posted @ 2018-10-31 13:46  絮絮墨恒  阅读(495)  评论(1编辑  收藏  举报