鼓捣delphi一年多了,以为对delphi 有一定的熟悉了 今天才发现原来什么都不知道,以下应该都是简单问题,但就是没明白,等搞明白了 我散分给大家
1. Application 是在Form单元中声明的Tapplication 型变量,这个东东是在什么
地方实例化的  Application.Initialize 做了些什么事情 2.以下是Tapplication.CreateForm的代码 
procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
var
  Instance: TComponent;
begin
  Instance := TComponent(InstanceClass.NewInstance); 
  TComponent(Reference) := Instance;
  try
    Instance.Create(Self); 
  except
    TComponent(Reference) := nil;
    raise;
  end;
  if (FMainForm = nil) and (Instance is TForm) then
  begin
    TForm(Instance).HandleNeeded;
    FMainForm := TForm(Instance);
  end;
end;
 2.1 var Reference 没有说明类型是怎么回事 从来没有见过好像也没有哪本书提到过  
 2.2 Instance := TComponent(InstanceClass.NewInstance) 难道不是实例化了一个Tcomponent对象吗?如果不是那他是干什么的?
 2.3 Instance.Create(Self) 这一句该如何解释? 变量不能自己实例化自己啊 不明白
 2.4 TComponent(Reference) := Instance; 这个是什么意思啊 ? 

解决方案 »

  1.   

    1,从字面上理解,它的意思就是初始化,但是仔细看看相关VCL,就知道通常这句什么也不做,一般情况下可以去掉!procedure TApplication.Initialize;
    begin
      if InitProc <> nil then TProcedure(InitProc);
    end;因为上面的InitProc一开始等于nil要用的话在initialization区域下写上类似代码即可:
    InitProc := @MyInitProc;MyInitProc是你希望在初始化阶段调用的过程:procedure MyInitProc;2.1,确实可以这么用,既然没定义就是无类型啊,所以后面用TComponent()强制转换为了TComponent实例procedure Test(var i);
    begin
      ShowMessage(IntToStr(Integer(i)));
    end;Test(n);自己试试吧2.2,NewInstance方法用来分配实例内存,加上TComponent用于返回一个TComponent实例的对象指针2.3,Self不是指自己,而是指Application,这里是指明Instance的宿主2.4,赋值,因为var Instance: TComponent;,做个类型转换综合理解,以Application.CreateForm(TForm1, Form1);为例,就是调用TForm1的方法完成内存分配,把实例的指针返回给Form1,如果还未指定主窗体,把当前窗体设为主窗体
      

  2.   

    老大都说了
    我就说头两句
    Instance := TComponent(InstanceClass.NewInstance); //创建了一个TComponent实例
      TComponent(Reference) := Instance; //将Reference强制转化成该实例,Reference可以理解为TObject类型
      

  3.   

    有关 InitProc  请参考DBTables.pas 的initialization部分代码
      

  4.   

    procedure TApplication.CreateForm(InstanceClass: TComponentClass; var Reference);
    var
      Instance: TComponent;
    begin
      Instance := TComponent(InstanceClass.NewInstance); 
    //注意InstanceClass
    //实际上是一个类引用,而NewInstance实际上是一个类方法
    //类方法在C++中为一个STATIC的函数
    //这一句的作用实际上是创造一个指定类的实例
      TComponent(Reference) := Instance;
    //对无类型的参数强制转直  
    try
       //注意SELF在对象方法中
      //强制制订对象的OWNER为APPLICAION
     Instance.Create(Self);
     
      except
        TComponent(Reference) := nil;
        raise;
      end;
    //第一个调用这个方法 TApplication.CreateForm的创建的窗口为主窗口 
    //Instance is TForM保证所创建的是一个TFORM的子类才把他做为子窗口
    if (FMainForm = nil) and (Instance is TForm) then
      begin
        TForm(Instance).HandleNeeded;
        FMainForm := TForm(Instance);
      end;
    end;