Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 援引最佳做法_C# - Fatal编程技术网

C# 援引最佳做法

C# 援引最佳做法,c#,C#,每次从创建元素以外的线程更新程序视图时,我都使用: if (this.table.InvokeRequired) { this.table.Invoke(new MethodInvoker(delegate { this.table.Controls.Add(newRow); this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count); })); } else {

每次从创建元素以外的线程更新程序视图时,我都使用:

if (this.table.InvokeRequired)
{
    this.table.Invoke(new MethodInvoker(delegate
    {
        this.table.Controls.Add(newRow);
        this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count);
    }));
}
else
{
    this.table.Controls.Add(newRow);
    this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count);
}
尽管这种方法效果很好,但我怀疑它是否是自2000年以来最好的做法

this.table.Controls.Add(newRow);
this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count); 
调用和不调用基本相同


有什么办法可以改进吗?

您可以将其放入一个方法中,然后该方法可以调用自身:

public void addRow(Control newRow) {
  if (this.table.InvokeRequired) {
    this.table.Invoke(new MethodInvoker(addRow), new object[]{ newRow });
  } else {
    this.table.Controls.Add(newRow);
    this.table.Controls.SetChildIndex(newRow, this.table.Controls.Count);
  }
}

语法可能不完全正确,但大致如下:

delegate void myedelegate(<mystuff>)
void UpdateSomething(<mystuff>)
if(this.invokerequired)
{
    mydelegate updater = new mydeleate(UpdateSomething);
    updater.invoke(new object[]{<mystuff>})
}
else
{
    //doupdate
}
delegate void myelegate()
void updateMething()
if(this.invokererequired)
{
mydelegate updater=新的mydelegate(UpdateMething);
invoke(新对象[]{})
}
其他的
{
//更新
}

另外,有关调用所需实践的良好指南,请参见

,如果您对使用PostSharp没问题,我建议您这样做。我会将通用代码放入操作/委托中,并将其传递到调用或在else中调用。我已编辑了您的标题。请参阅“”,其中的共识是“不,他们不应该”。