gpt4 book ai didi

c# - 使用 GetType().Name 在事件处理程序中转换发件人对象

转载 作者:IT王子 更新时间:2023-10-29 04:29:16 28 4
gpt4 key购买 nike

我有一个文本框和 RichTextBox 的事件处理程序。代码是一样的,但是

在处理程序 #1 中我这样做:

RichTextBox tb = (RichTextBox)sender

相应地在处理程序 #2 中:

TextBox tb = (TextBox)sender

这样我就可以完全操纵发送控件了。如何根据其类型将发送对象转换为 TextboxRichTextbox

sender.GetType().Name

然后在运行时创建控件并使用它?这样我只需要一个事件处理函数:更少的代码,更少的错误,更容易维护和 DRY :-)

最佳答案

您永远不必转换。我刚开始的时候也是这样想的,这个“模式”是不正确的,而且不合逻辑。

你最好的选择是使用类似的东西:

if (sender is TextBox)
{
TextBox tb = (TextBox)sender;
}
else if (sender is RichTextBox)
{
RichTextBox rtb = (RichTextBox)sender;
}
else
{
// etc
}

关于c# - 使用 GetType().Name 在事件处理程序中转换发件人对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/634112/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com