【发布时间】:2009-07-03 13:40:51
【问题描述】:
这是我在控件上调用的扩展方法:
public static void Invoke<T>(this T c, Action<System.Windows.Forms.Control> DoWhat)
where T:System.Windows.Forms.Control
{
if (c.InvokeRequired)
c.Invoke(o=> DoWhat(c) );
else
DoWhat(c);
}
ds 是一个强类型数据集。
这有效:
Action<DataGridView> a = row => row.DataSource = ds.bLog;
this.dataGridView1.Invoke(a);
这不会编译:
this.dataGridView1.Invoke<DataGridView>(o => o.DataSource = ds.bLog);
并说 System.Windows.Forms.Control 不包含“数据源”的定义...
我真的必须把它分成两行吗? 为了清楚/安全,我应该调用通用扩展方法 InvokeSafe 吗?
编辑:扩展方法已修改(有效,但我想删除命名委托要求):
private delegate void myDel();
public static void InvokeSafe<T>(this T c, Action<T> DoWhat) where T : Control
{
myDel d = delegate() { DoWhat(c); };
if (c.InvokeRequired)
c.Invoke(d);
else
DoWhat(c);
}
我似乎无法弄清楚如何将myDel 分解为块中的匿名委托?
【问题讨论】:
-
显然我在 c.Invoke(o=> DoWhat(c) );因为它是递归方法,而不是调用控件的 .Invoke(delegate) 方法。
标签: c# multithreading generics user-interface extension-methods