2009-04-08 56 views
11

我使用下面的代碼來訪問我的窗體上的屬性,但今天我想寫一些東西到一個ListView,這需要更多的參數。C#如何調用多個參數

public string TextValue 
    { 
     set 
     { 
      if (this.Memo.InvokeRequired) 
      { 
       this.Invoke((MethodInvoker)delegate 
       { 
        this.Memo.Text += value + "\n"; 
       }); 
      } 
      else 
      { 
       this.Memo.Text += value + "\n"; 
      } 
     } 
    } 

如何添加多個參數以及如何使用它們(值,值)?

回答

27

編輯 - 我想我誤會了原來的問題)

只需讓它的方法,而不是一個屬性:

public void DoSomething(string foo, int bar) 
{ 
    if (this.InvokeRequired) { 
     this.Invoke((MethodInvoker)delegate { 
      DoSomething(foo,bar); 
     }); 
     return; 
    } 
    // do something with foo and bar 
    this.Text = foo; 
    Console.WriteLine(bar); 
} 
0

一般地,你可以做如下

  • 在C#2012/Net 4.5中創建一個名爲Lambda的Windows Forms應用程序項目
  • 在For M1形式,插入一個名爲label1的
  • 按F4打開屬性Form1的(不是label1的屬性)
  • 點擊事件視圖(圖標與雷霆)
  • 在窗體Closing事件雙擊標籤。一個事件處理程序將被創建。
  • 現在不介意事件處理程序。稍後將由另一個取代;
  • 選擇並清除Form.cs中的所有代碼(Ctrl-A/Delete鍵)
  • 將以下代碼複製並粘貼到Form1.cs中;

using System; 
using System.Collections.Generic; 
using System.ComponentModel; 
using System.Data; 
using System.Drawing; 
using System.Linq; 
using System.Linq.Expressions; 
using System.Text; 
using System.Threading; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Diagnostics; 
namespace Lambda1 
{ 
public partial class Form1 : Form 
{ 

    System.Timers.Timer t = new System.Timers.Timer(1000); 
    Int32 c = 0; 
    Int32 d = 0; 
    Func<Int32, Int32, Int32> y; 

    public Form1() 
    { 

     InitializeComponent();   
     t.Elapsed += t_Elapsed; 
     t.Enabled = true; 
    } 

    void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 
    { 
     c = (Int32)(label1.Invoke(y = (x1, x2) => 
       { label1.Text = (x1 + x2).ToString(); 
           x1++; 
           return x1; }, 
           c,d)); 
     d++; 
    } 

    private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
    { 
     t.Enabled = false; 
    } 
} 

} 

這段代碼做的是:創建

計時器。經過事件處理程序

void t_Elapsed(object sender, System.Timers.ElapsedEventArgs e) 

都會被調用1000ms的

的label1.Text將這一事件處理程序內進行更新。如果沒有調用,將有發出

要使用新的值更新label1.Text一個線程,該代碼使用


c = (Int32)(label1.Invoke(y = (x1, x2) => { label1.Text = (x1 + 
x2).ToString(); x1++; return x1; }, c,d)); 

請看到,c和d是作爲參數傳遞給Invoke函數中的x1和x2,並在Invoke調用中返回x1。

在此代碼中插入變量d,以顯示調用Invoke時如何傳遞多個變量。

相關問題