使用GetType()在事件处理程序中转发发件人对象.名称

tfl*_*tfl 24 c# late-binding

我有一个文本框和RichTextBox的事件处理程序.代码完全相同,但是

在处理程序#1中我做:

RichTextBox tb = (RichTextBox)sender
Run Code Online (Sandbox Code Playgroud)

因此在处理程序#2中:

TextBox tb = (TextBox)sender
Run Code Online (Sandbox Code Playgroud)

这样做我可以完全操纵发送控件.我想知道的是如何使用发送对象根据其类型将发送对象强制转换为Textbox或RichTextbox

sender.GetType().Name
Run Code Online (Sandbox Code Playgroud)

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

lep*_*pie 30

你永远不必投.当我开始时,我曾经以同样的方式思考,这种"模式"是不正确的,而且不是很合乎逻辑.

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

if (sender is TextBox)
{
  TextBox tb = (TextBox)sender;
}
else if (sender is RichTextBox)
{
  RichTextBox rtb = (RichTextBox)sender;
}
else
{
  // etc
}
Run Code Online (Sandbox Code Playgroud)

  • 一旦确定了对象的类型,您实际上就是在进行转换,因此您必须进行转换,但这绝对是正确的方法,因为它不依赖(缓慢的)反射。 (2认同)

Mar*_*ram 7

我知道这是一个非常古老的帖子,但在框架4中,您可以将发件人转换为控件:

Control cntrl = (Control)sender;
cntrl.Text = "This is a " + sender.GetType().ToString();
Run Code Online (Sandbox Code Playgroud)

请注意,您只能引用所有不同控件共有的控件(即Text).


stu*_*rtd 5

而不是您可以使用“”的类型名称。

如果您只想知道类型而不需要对象引用:

if (sender is RichTextBox)
{
    // ...
}
else if (sender is TextBox)
{
    // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,您通常确实需要对象:C#7 有一个很好的语法,可以让您测试并获取内联值:

if (sender is RichTextBox richTextBox)
{
    richTextBox.Text = "I am rich";
}
else if (sender is TextBox textBox)
{
    textBox.Text = "I am not rich";
}
Run Code Online (Sandbox Code Playgroud)


Kie*_*ron 3

根据您需要的属性,您可以将发送者强制转换为 TextBoxBase,因为 TextBox 和 RichTextBox 都继承自该子类。