【问题标题】:Why does my Timer come back null when I have inherited it?为什么我的 Timer 在我继承后返回 null?
【发布时间】:2011-10-03 11:28:05
【问题描述】:

我有接口:

 public interface IProcess
    {
        void Step_One();
        void Step_Two();
        Timer ProcessTimer{get; set;}
    }

基类..

 public class ProcessBase
    {
        protected Timer processTimer;
        public Timer ProcessTimer{get{ return processTimer;}set{processTimer=value;}}



        //sets up all the common objects
        public ProcessBase() 
        {


        }

        //This constructor will call the default constructor ^
        protected ProcessBase(long intervalArg) : this()
        {
            processTimer = new Timer(intervalArg);
            processTimer.Enabled = true;

        }

    }

具体类

public class ReportedContentProcess : ProcessBase, IProcess
{

    public ReportedContentProcess(): base(5000)
    {

    }

    public void Step_One()
    {
    }

    public void Step_Two()
    {
    }
}

但是当我试图在工厂里把它弄出来时......

public static class ProcessFactory
    {

        public static List<IProcess> GetProcessors()
        {

            ReportedContentProcess.ReportedContentProcess reportedContentProcess = new ReportedContentProcess.ReportedContentProcess();

            List<IProcess> retProcesses = new List<IProcess>();
            retProcesses.Add(reportedContentProcess);
            return retProcesses;

        }   
    }

然后将处理程序附加到计时器...

processorsForService = ProcessFactory.GetProcessors();


                foreach(IProcess p in processorsForService)
                {
                    p.ProcessTimer.Elapsed += new ElapsedEventHandler(IProcess_Timer_Elapsed);
                }

我收到一个运行时错误,指出 p.ProcessTimer 为空。为什么是这样?我在基类中继承和实例化无法理解为什么它为空。我什至将它包含在界面中...

【问题讨论】:

  • 为什么你有2个构造函数?为什么没有一个初始化 Timer 和所有其他对象的对象?
  • sn-ps 没有解释。使用调试器。在两个构造函数上设置断点。
  • 我复制了代码,它运行良好,您使用的是什么 .net 版本/ide?​​span>
  • 它应该可以工作。我认为您正在执行计时器之前的最后一个代码块,您是否尝试过单步执行您的程序?
  • > ReportedContentProcess.ReportedContentProcess

标签: c# oop design-patterns factory-pattern


【解决方案1】:

我看到您仅在第二个构造函数中初始化 Timer。如果调用了默认的(即没有参数的构造函数)怎么办?

【讨论】:

  • 被调用的构造函数是另一个。这不是这里的问题,尽管您已经说明了这些课程的设计方式。
  • @VdesmedT 他的代码不是很清楚。这个构造函数可能会在以后调用导致NullReferenceException
猜你喜欢
  • 1970-01-01
  • 2022-01-10
  • 2020-06-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多