首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > .NET >

有关组件创建时默认值解决办法

2012-03-09 
有关组件创建时默认值unitUnit1interfaceusesWindows,Messages,SysUtils,Variants,Classes,Graphics,Cont

有关组件创建时默认值
unit   Unit1;

interface

uses
    Windows,   Messages,   SysUtils,   Variants,   Classes,   Graphics,   Controls,   Forms,
    Dialogs,   StdCtrls;

    Type
                TcyEdit   =   Class(TEdit)
                private
                                fIsBol:   Boolean;
                published
                                property   IsBol:   Boolean   Read   fIsBol   Write   fIsBol   Default   True;
    end;

type
    TForm1   =   class(TForm)
        Button1:   TButton;
        procedure   Button1Click(Sender:   TObject);
    private
        {   Private   declarations   }
    public
        {   Public   declarations   }
    end;

var
    Form1:   TForm1;

implementation

{$R   *.dfm}

procedure   TForm1.Button1Click(Sender:   TObject);
var
                cyEdit:   TcyEdit;
begin
                cyEdit   :=   TcyEdit.Create(Self);
                cyEdit.Parent   :=   Form1;
//                 cyEdit.IsBol   :=   true;                   在设计时不能进行设置么?

                if   cyEdit.fIsBol     then
                                ShowMessage( 'Yes ')
                else
                                ShowMessage( 'No ');

                if   cyEdit.IsBol     then
                                ShowMessage( 'Yes ')
                else
                                ShowMessage( 'No ');
end;

end.

1、cyEdit的值永远为false
2、设计时不能进行定义么?


[解决办法]
你的TcyEdit类的属性IsBol的所谓默认值True,只是在Published部分进行了申明,而TcyEdit类的构造函数,却仍然用的是其父类TEdit的构造函数,TEdit没有IsBol这个属性,所以...

你需要覆盖父类的构造函数,并在构造时,对属性进行赋值。如下:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

Type
TcyEdit = Class(TEdit)
private
fIsBol: Boolean;
public
constructor Create(AOwer : TComponent);override;//覆盖父类的构造方法
published
property IsBol: Boolean Read fIsBol Write fIsBol Default True;


end;

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

constructor TcyEdit.Create(AOwer : TComponent);//TcyEdit类的构造函数
begin
inherited Create(AOwer);
FIsBol := True;//这是对私有成员赋值。对属性IsBol赋值也可
end;

procedure TForm1.Button1Click(Sender: TObject);
var
cyEdit: TcyEdit;
begin
cyEdit := TcyEdit.Create(Self);
cyEdit.Parent := Form1;
// cyEdit.IsBol := true; 在设计时不能进行设置么?
if cyEdit.fIsBol then ShowMessage( 'Yes ') else ShowMessage( 'No ');
if cyEdit.IsBol then ShowMessage( 'Yes ') else ShowMessage( 'No ');
end;

end.

热点排行