In Delphi, I can define a range of characters or integ开发者_如何转开发ers as demonstrated below:
var
a,i: integer;
b: char;
intrange: 1..9;
charrange: 'α' .. 'ζ';
begin
for a := low(IntRange) to high(IntRange) do
begin
Memo1.Lines.Add('Integer Range Iteration = ' + intToStr(a) ) ;
end;
i:=0;
for b := low(charrange) to high(charrange) do
begin
i := i + 1;
Memo1.Lines.Add('Character Range Iteration = ' + intToStr(i) + ', value = ' + b +' ord '+ inttostr(ord(b))) ;
end;
end;
How can I pass a range as a parameter to a function?
You can use subrange types:
type
TCharrange = 'α' .. 'ζ';
procedure MyFunction(Char: TCharrange);
Now you can do
MyFunction('γ');
whereas
MyFunction('a');
won't work.
As I understand your question you want to pass a range rather than a character that is within some specified range. If that is a correct understanding then you would need to pass two parameters (min and max) or perhaps wrap them up in a record.
You can try sets in certain cases, for example:
type
TMyRange = 1..5;
TMyRangeSet = Set of TMyRange;
procedure A(const V: TMyRangeSet);
var X : TMyRange;
begin
for X := Low(TMyRange) to High(TMyRange) do
if X in V then { included }
end;
begin
A([3..4]);
end.
I beleive you'd need to define it as a type first, something like:
type
TMyRange = 1..2;
then:
function Whatver(Range: TMyRange): Boolean;
begin
end;
I am rather new to generics, but I think that this might be a rather neat solution to the second interpretation (the David Heffernan interpretation) of your problem.
type
TRange<T> = record
MinVal: T;
MaxVal: T;
constructor Create(AMinVal, AMaxVal: T);
end;
TCharrange = TRange<Char>;
// TIntrange = TRange<Integer>;
// etc.
constructor TRange<T>.Create(AMinVal, AMaxVal: T);
begin
MinVal := AMinVal;
MaxVal := AMaxVal;
end;
Now you can do
procedure MyFunction(Char: TCharrange);
begin
ShowMessage(Char.MinVal);
ShowMessage(Char.MaxVal);
end;
procedure TForm1.Button1Click(Sender: TObject);
var
r: TCharrange;
begin
r.Create('a', 'c');
MyFunction(r);
end;
精彩评论