按钮的继承

ehs*_*d18 3 c# inheritance winforms

我设计了一个按钮

如何继承此按钮的其余部分?

按键


这种继承方法是否属实?

我的代码:

    public class MyButton : Button
{

    public MyButton()
        : base()
    {
        // set whatever styling properties needed here
        this.ForeColor = Color.Blue;
        this.Click += new EventHandler(MyButton_Click);
        this.BackColor = Color.Red;
    }

    void MyButton_Click(object sender, EventArgs e)
    {
        MessageBox.Show("yes");
    }
}
Run Code Online (Sandbox Code Playgroud)

为什么不改变背景颜色?

背景颜色


所有房产都可能有所变化

除了背景颜色

这是正常的事吗

没有解决方案?

Ada*_*ear 9

您可以创建一个新类,为标准Button创建子类,并在构造函数中进行样式调整.完成后,重建项目,新组件应显示在顶部的工具箱中.使用它代替标准按钮,你应该好好去.

public class MyButton : Button
{
    public MyButton() : base()
    {
        // set whatever styling properties needed here
        ForeColor = Color.Red;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 是的,但是你确定你想要一个简单的类来改变ForeColor吗? (4认同)

Che*_*hen 5

我假设您想要的是:定义 10 个按钮和样式(设置几个属性)button1,您希望其余 9 个按钮与 button1 相同。这不是C# 中的继承。为了满足您的要求,您可以将这 10 个按钮放在一个列表/集合/数组/等中……获取按钮的一种方法可能如下所示:

var buttons = container.Controls.OfType<Button>();
Run Code Online (Sandbox Code Playgroud)

然后循环列表以设置属性:

foreach(var button in buttons)
{
   //set the common properties.
}
Run Code Online (Sandbox Code Playgroud)