wul*_*pro 5 c# language-features delegates
是否可以使用匿名委托来返回对象?
像这样的东西:
object b = delegate { return a; };
Run Code Online (Sandbox Code Playgroud)
是的,但只能通过调用它:
Func<object> func = delegate { return a; };
// or Func<object> func = () => a;
object b = func();
Run Code Online (Sandbox Code Playgroud)
当然,以下是更简单的...
object b = a;
Run Code Online (Sandbox Code Playgroud)
在注释中,提到了跨线程异常; 这可以修复如下:
如果委托是我们想要从 BG线程在UI线程上运行的东西:
object o = null;
MethodInvoker mi = delegate {
o = someControl.Value; // runs on UI
};
someControl.Invoke(mi);
// now read o
Run Code Online (Sandbox Code Playgroud)
或者反过来(在BG上运行委托):
object value = someControl.Value;
ThreadPool.QueueUserWorkItem(delegate {
// can talk safely to "value", but not to someControl
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6016 次 |
| 最近记录: |