3

私は次のように から拡張しましControlた:

public class Ctrl : Control
{
     public Boolean HasBorder { get; set; }
     public Boolean ShouldDrawBorder { get; set; }

     protected override void OnPaint(PaintEventArgs e)
     {
          if(CertainConditionIsMet)
          {
               // Then draw the border(s).
               if(this.BorderType == BorderTypes.LeftRight)
               {
                   // Draw left and right borders around this Ctrl.

               }
           }

           base.OnPaint(e);
     }
}

しかし、 a を に追加するnew TextBox();と、Formからではなく Control から継承されCtrlます。Ctrlすべての新しいコントロールを代わりに継承させるにはどうすればよいですか?

4

2 に答える 2

4

から継承する各コントロールを手動で再作成する必要がありますCtrl。例えば

public class TextBoxCtrl : Ctrl
{
  /* implementation */
}

編集:

車輪の再発明を避けるために、私はおそらく次の方法でそれに取り組みます。

まず、追加されたプロパティをインターフェイスの一部にして、ハンドオフできるコントロールにします。

public interface ICtrl
{
    Boolean HasBorder { get; set; }
    Boolean ShouldDrawBorder { get; set; }
}

次に、UI の機能強化を処理するヘルパー メソッドを (別のクラスで) 作成します。

public static class CtrlHelper
{
    public static void HandleUI(Control control, PaintEventArgs e)
    {
        // gain access to new properties
        ICtrl ctrl = control as ICtrl;
        if (ctrl != null)
        {
            // perform the checks necessary and add the new UI changes
        }
    }
}

次に、カスタマイズする各コントロールにこの実装を適用します。

public class TextBoxCtrl : ICtrl, TextBox
{
    #region ICtrl

    public Boolean HasBorder { get; set; }
    public Boolean ShouldDrawBorder { get; set; }

    #endregion

    protected override void OnPaint(PaintEventArgs e)
    {
        CtrlHelper.HandleUI(this, e);

        base.OnPaint(e);
    }
}
/* other controls */

これで、各コントロールの元の機能のほとんどを保持し、その継承を保持し、最小限の労力で 1 つの場所で機能を拡張します (または元のコントロールに変更します)。

于 2013-07-23T12:38:50.317 に答える
1

必要なすべてのクラスをやり直さない限り、これを行うことはできません。たとえば、次のようになります。

public class ExtendedTextBox : Ctrl
{
    //implement the thing here
}
于 2013-07-23T12:39:51.243 に答える