generics.nullable.pas

来自「Delphi 2009 Generics class. this is an e」· PAS 代码 · 共 57 行

PAS
57
字号
unit Generics.Nullable;

interface

uses
  SysUtils, TypInfo;

resourcestring
  sCantConvertNilToTypeName = 'Ne peut convertir nil en %s';
  sCantConvertNil = 'Ne peut convertir nil';
  sOnlyValidValueIsNil = 'La seule valeur valide est nil';

type
  TNullable<T> = record
  private
    FValue: T;
    FIsNil: Boolean;
  public
    class operator Implicit(const Value: T): TNullable<T>;
    class operator Implicit(Value: Pointer): TNullable<T>;
    class operator Implicit(const Value: TNullable<T>): T;

    property IsNil: Boolean read FIsNil;
    property Value: T read FValue;
  end;

implementation

class operator TNullable<T>.Implicit(const Value: T): TNullable<T>;
begin
  Result.FValue := Value;
  Result.FIsNil := False;
end;

class operator TNullable<T>.Implicit(Value: Pointer): TNullable<T>;
begin
  Assert(Value = nil, sOnlyValidValueIsNil);
  Result.FIsNil := True;
end;

class operator TNullable<T>.Implicit(const Value: TNullable<T>): T;
begin
  if Value.IsNil then
  begin
    if TypeInfo(T) = nil then
      raise EConvertError.Create(sCantConvertNil)
    else
      raise EConvertError.CreateFmt(sCantConvertNilToTypeName,
        [GetTypeName(TypeInfo(T))]);
  end;

  Result := Value.FValue;
end;

end.

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?