2011-09-25 58 views
1

首先,我的英语不是很好,所以如果你可以善良,它将不胜感激。谢谢。通过一个有针对性的方法作为参数

现在我的问题,就像我在标题中所说的,我想在另一个方法中传递一个“方法名称”作为参数。就像一张图片胜过千言万语,还有就是我的功能块:

public void RemoveDecimalPoints(TextBox txtBoxName, Func<string, TextBox> txtBoxMethod) 
    { 
     //Some Code 

     txtBoxName.KeyPress += new KeyPressEventHandler(txtBoxMethod); 
    } 

我想第二个参数指向这个另一种方法:

private void txtIncomeSelfValue1_KeyPress(object sender, KeyPressEventArgs e) 
    { 
     //Some Code 
    } 

很抱歉,如果我不是为一些明确的,我缺少一些词汇...

感谢您的帮助。

+0

尝试使用代理。 –

回答

2

假设你正在呼吁从包含txtIncomeSelfValue1_KeyPress方法相同的类此RemoveDecimalPoints方法,你可以通过这样的:

RemoveDecimalPoints(someTextBox, this.txtIncomeSelfValue1_KeyPress); 

,但你将不得不修改签名Func<string, TextBox>不匹配txtIncomeSelfValue1_KeyPress方法:

public void RemoveDecimalPoints(TextBox txtBoxName, KeyPressEventHandler txtBoxMethod) 
{ 
    //Some Code 
    txtBoxName.KeyPress += txtBoxMethod; 
} 
+0

不得不给你一个upvote - 你的答案是(独立)几乎完全一样的我的。 :-) – Enigmativity

+0

坦克为您提供帮助!我试过,但不是好方法,在txtBoxName.KeyPress + = txtBoxMethod;我正在使用txtIncomeSelfValue1.KeyPress + = new KeyPressEventHandler(txtBoxMethod);我很接近!大声笑^^ – geek1983

1

如果你感到快乐写你这样的代码:

RemoveDecimalPoints(txtBoxName, txtIncomeSelfValue1_KeyPress); 

那么你可以使用:

public void RemoveDecimalPoints(
    TextBox txtBoxName, 
    KeyPressEventHandler txtBoxMethod) 
{ 
    //Some Code 

    txtBoxName.KeyPress += txtBoxMethod; 
} 

如果你想使用string,那么你需要使用反射和签名将需要看起来像这样:

void RemoveDecimalPoints(TextBox txtBoxName, string txtBoxMethod) 
+0

感谢您的帮助,这是很好的回答^^ – geek1983

相关问题