Função de argumentos infinitos para Delphi e Lazarus
Quando precisamos criar uma função que deverá tratar vários tipos de argumentos geralmente criamos funções que aceitam como parâmetros Arrays dinâmicos, ou simplesmente criamos várias funções sobrecarregadas.
Mas e quando a função deve receber argumentos de tipos diferentes? Como a função writeln do Pascal/Delphi ou a printff do C ?
O Array of Const
Você pode declarar uma função como recebendo um array of const. Ela aceitará qualquer tipo de argumento, entre [], e você poderá inclusive passar argumentos de tipos diferentes. Você pode varrer a lista de argumentos e verificar de que tipo eles são, para tomar providências diferentes dependendo do tipo.
Você pode passar também objetos e usar a RTTI para identifica-los. Considere o seguinte código:
function FormataMensagem(const args: array of const):string;
var
i: integer;
begin
for i := low(args) to high(args) do
begin
case args[i].VType of
vtAnsiString: Result := Result + ' ' + AnsiString(args[i].VAnsiString);
vtInteger: Result := Result + ' ' + IntToStr(args[i].VInteger);
{continua...}
end;
end;
end;
E você pode testar assim:
ShowMessage(FormataMensagem(['Post Número', 1, 'No mês', 2, 'de', 2010]));
Eu simplesmente passo 3 strings e 3 inteiros, porque trato atualmente só esse tipo de dado, mas você pode incrementar esse método para trabalhar com qualquer tipo, e até obter informações do tipo.
Para terminar, o link abaixo explica a diferença entre Open Array, Dynamic Array e o Array of Const, também chamado de TVarRec.
http://rvelthuis.de/articles/articles-openarr.html
Até a próxima!
http://vitorrubio.blogspot.com/



1 comment
Esse blog será muito útil... sou estudante de Ciência da Computação! =))
Valeu!!
Post a Comment
All comments are read and moderated before published.
For every comment
- ALL CAPS or grammatical errors will not be tolerated;
- Do not promote other blogs or websites;
- Do not add unnecessary links in the content of your comment;
- If you want to leave your URL, use the OpenID;
- Promote your e-mail only if really needed;
- Threats, insults or attacks are not allowed;
- Your comment must be related to the subject of the article;
Questions?
- Read all the answers;
- Ask if you can not find the answer;
Comments should contain only the following topics:
- Questions;
- Suggestions;
- Thanks;
- Tips related;
Every comment is a personal opinion of the reader. The authors are not responsible for the content of any comments made by the commenter(s). The authors are also not responsible for knowing whether the content of Your comment is breaking the law in other countries or jurisdictions.