【问题标题】:inheriting from a Forms.Timer从 Forms.Timer 继承
【发布时间】:2011-10-28 07:44:08
【问题描述】:

我想从 Forms.Timer 控件继承,因为我想向它添加一个方法,但是它需要在实例化时传递一个 System.ComponentModel.Container 给它,这需要传递给基类.

我有以下无法编译的内容:

class Timer : System.Windows.Forms.Timer
    {

        public Timer() : base (System.ComponentModel.Container)
        {

        }

        public static bool IsTimeToActivate()
        {
            return false;
        }
    }

容器参数被标记为:

此时类名无效

我在这里缺少一些基本的理解吗?

【问题讨论】:

    标签: c# .net winforms windows-services


    【解决方案1】:

    如果您只想为计时器添加一个方法,我认为extension method 是一个更好的解决方案:

     public static class TimerExtensions
     {
         public static MyTimerExtension(this Timer timer)
         {
             // use timer here just as any method parameter
         }
     }
    
     //usage
    
     timer1.MyTimerExtension();
    

    【讨论】:

    • 我也同意——我已经用这种方法了
    【解决方案2】:

    你需要一个像这样的构造函数:

    public Timer(System.ComponentModel.Container container) : base (container)
    {
    }
    

    或者这个

    public Timer() : base()
    {
    }
    

    【讨论】:

    • 扩展这个,如果计时器的构造函数需要一个容器,你需要传递一个容器对象,它已经传递给你的构造函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多