我知道代表們已經在SO上做了很多工作,但有時在我看到自己的東西之前,它並沒有點擊。我看下面的表格代碼和我知道它可以更好。在這種情況下使用委託是明智的嗎?
應該指出,我正在使用包含我想要使用的方法的「模型類」'_model'。
- _model.LoadItemType1需要一個字符串,但不返回值(負載文本,並建立對象)。
- _model.LoadTotallyDifferentItem也需要一個字符串,但構建不同的對象。
還是我 - (兩種方法都超載過不帶參數 - 這是否複雜的事情?)
... ...
private string Item1;
private string Item2;
private void button1Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
if (OFD.ShowDialog() == DialogResult.OK)
{
// Removed TRY-CATCH block for simplicity
Item1= OFD.FileName;
_model.LoadItemType1(Item1);
}
//Some other code to update form etc.
}
private void button2Click(object sender, EventArgs e)
{
OpenFileDialog OFD = new OpenFileDialog();
if (OFD.ShowDialog() == DialogResult.OK)
{
// Removed TRY-CATCH block for simplicity
Item2 = OFD.FileName;
_model.LoadTotallyDifferentItem(Item2);
}
//Some other code to update form etc.
}
所有身邊的東西是相似嘗試捕捉相同的,我仍然希望它從按鈕點擊,仍然採取字符串。我想我應該能夠使用一些簡單地傳遞我正在運行的方法的東西 - 例如_model.LoadItemType1,並且具有執行try-catch和其他代碼的一種方法。我視覺會是這樣......
string Item1;
string Item2;
private void DoThis(/* take my Method namne here */, ref string s)
{
// all the code from above but with the appropriate method and string reference
}
private void button1Click(object sender, EventArgs e)
{
DoThis(_model.LoadItemType1, ref Item1);
}
private void button2Click(object sender, EventArgs e)
{
DoThis(_model.LoadTotallyDifferentItem, ref Item2);
}
有了這個,我可以補充一點,加載的文件類型,也不會需要複製大量的代碼按鈕。
我已經嘗試了許多這樣的例子,但總是在試圖實現它們時似乎絆倒了。我也有點困惑,並嘗試混合不同的概念。我嘗試傳遞一個Func,但它似乎想要一個返回類型,並且我的方法不會返回任何內容,因此我已移至代表。
任何人都可以幫助我轉換我的例子嗎?
看起來不錯......沒有拿起「行動」......讓我試試看。 –
Sisyphus
2013-04-29 01:39:39
在我的調用代碼中,我試圖讓這個工作,但它不會採取我的「行動」 - 任何想法? {Action aMethod = _model.LoadType1; LoadData(aMethod,Item1);} – Sisyphus 2013-04-29 01:52:51
Got it!我根本就沒有那麼做......(現在正在工作)...動作 aMethod = _model.LoadItemType1; LoadData(aMethod,ref Item1); –
Sisyphus
2013-04-29 01:58:49