Why use property in a class?

后端 未结 7 439
闹比i
闹比i 2020-12-17 00:34

I was just wondering about why should I use property in a class instead of \"normal\" variables (class attributes?). What I mean is this:

TSampleClass = clas         


        
相关标签:
7条回答
  • 2020-12-17 01:16

    One of main reason of using properties (regardless of it's more OO) is the validation of the input, for example if you need to limit the age of an employee class to be in valid range like 18..40

      TEmp = class
      private
        FName: string;
        FAge: Integer;
        procedure SetAge(const Value: Integer);
        procedure SetName(const Value: string);
      published
        property Name:string read FName write SetName;
        property Age:Integer read FAge write SetAge;
      end;
    
    .....
    
    procedure TEmp.SetAge(const Value: Integer);
    begin
      if not (Value in [18..40]) then
        raise Exception.Create('Age must be between 18 and 40')
      else
        FAge := Value;
    end;
    
    0 讨论(0)
提交回复
热议问题