initializing private var creates AccessViolation
Comming from a C# background I'm trying to learn Delphi. I encounter an Access violation when in my form I press a button that creates a TLight instance. Wherever I try to access my private FState I get an access violation.
What am I missing?
unit Light;
interface
uses sysUtils;
type
  TLightStates = (Red, Orange, Green);
type
  TLight = class
    private
      Fstate : TLightStates;
    published
      Constructor Create(); overload;
      procedure SetState(const Value: TLightStates);
      Property State : TLightStates
        rea开发者_高级运维d Fstate
        write SetState;
  end;
implementation
{ TLight }
    constructor TLight.Create;
    begin
      Fstate := TLightStates.Red;
    end;
    procedure TLight.SetState(const Value: TLightStates);
    begin
      Fstate := Value;
    end;
end.
Did you create an object in your test code where the property State is set?
var
  x: TLight;
begin
  x := TLight.Create;
  x.Light := Orange;
  x.Free; 
end;
Looking at the code this should work correctly.
One other thing: why did you specify the contructor with overload: you derive from TObject and it does not have a virtual constructor, so overload should not be specified here.
One comment about the above piece of code :
var
  x: TLight;
begin
  x := TLight.Create;
  TRY  
    x.Light := Orange;
  FINALLY
    x.Free; 
  END;
end;
"try" and "finally" (uppercase used above for readability) ensure that x will be freed. As you might know by now, there is no garbage collection in Delphi so freeing your objects is a must...
About your initial piece of code : Your create should be virtual and public. Minor comments :
- TLightStates = (Red, Orange, Green) should actually be TLightState = (Red, Orange, Green) (no "s" since adding an "s" would usually mean a set of TLightState)
- Your SetState procedure should ideally be protected instead of published.
hth, kuzkot
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论