如何为继承的属性添加功能?

时间:2011-07-31 20:39:25

标签: c# wpf

我按照这篇文章中的说明进行操作:how to create Multiple user control that pointing single code behind file in silverlight 4

这是我的代码中的一个例子。

public class MyCommonUserControl : UserControl
{
    public static DependencyProperty CustomProperty = DependencyProperty.Register(
        "CustomProperty", typeof(int), typeof(MyCommonUserControl));

     public int CustomProperty
     {
         get
         {  
             return (int)GetValue(TypeProperty);
         }
         set
         {
             SetValue(TypeProperty, value);
             Extension();
         }
     }

     public virtual void Extension()
     {
     }
}

public class FirstMyCommonUserControl : MyCommonUserControl 
{
     public FirstMyCommonUserControl()
     {
         InitializeComponent();
     }

     public override void Extension()
     {
         base.Extension();

         // Do something
     }
}

如上所示,我正在使用继承。这段代码对我有用,因为我有几个自定义控件,其中一个是FirstMyCommonUserControl类,它覆盖了虚拟方法,我可以为这个特定类添加一些东西。然后我这样做:

    MyCommonUserControl A;
    int number;

    private void button1_Click(object sender, RoutedEventArgs e)
    {            
        switch (number)
        {
            case 1:
            case 2:
            case 3:
            case 4:
                A = new FirstMyCommonUserControl();
                A.CustomProperty = number;

                canvas1.Children.Add((FirstMyCommonUserControl)A);
                break;
            case 5:
            case 6:
            case 7:
            case 8:
                A = new AnotherMyCommonUserControl();
                A.CustomProperty = number;

                canvas1.Children.Add((AnotherMyCommonUserControl)A);
                break;
        }
    }

每个特定的类都需要在CustomProperty中做更多的事情。我使用虚拟方法并覆盖它。我不知道这样做是否是最好的方法。

1 个答案:

答案 0 :(得分:1)

属性也可以是虚拟的,而不仅仅是方法。所以你可以写点像

public class MyCommonUserControl : UserControl
{     
    public virtual int CustomProperty     
    {         
        get { return (int)GetValue(TypeProperty); }
        set { SetValue(TypeProperty, value); }
    }
}

public class FirstMyCommonUserControl : MyCommonUserControl 
{
    public override int CustomProperty     
    {         
        get 
        { 
            // Do something
            return base.CustomProperty;
        }
        set 
        { 
            // Do something
            base.CustomProperty = value;
        }
    }
}

虽然这个更好是否值得商榷。

此外,您的表达中不需要演员:

canvas1.Children.Add((FirstMyCommonUserControl)A);

你可以写:

canvas1.Children.Add(A);