Comando Case no Delphi
O Comando CASO (Case) no Delphi)
Fala galera do Show Delphi, tudo beleza? Hoje vamos falar sobre uma dúvida muito recorrente aqui na comunidade, principalmente entre os que estão começando.
Então vamos lá:
O Case pode ser entendido como uma forma de colocar de forma organizada uma sequencias de IFs.
Podemos dizer que a instrução Case é mais elegante, mais eficiente e mais fácil de manter do que vários alinhamentos de if.
Versão 2. É usada para declarações de Registros. É então chamado de Variante. Ele fornece um meio de mapear dois ou mais conjuntos diferentes de declarações na mesma seção do registro.
É usado principalmente ao lidar com diferentes tipos de conjunto de dados para um registro, onde os conjuntos de dados têm principalmente o mesmo conteúdo. Veja o exemplo para esclarecimento.
O Case realmente é usado para uma grande gama de situações, vejamos um exemplo:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| var
number : Integer;
begin
number := 17;
// cálculos também podem ser usados no case
Case number mod 2 of
0 : ShowMessage(IntToStr(Number)+' mod 2 = 0');
1 : ShowMessage(IntToStr(Number)+' mod 2 = 1');
else ShowMessage(IntToStr(Number)+' mod 2 é desconhecido');
end;
end; |
var
number : Integer;
begin
number := 17;
// cálculos também podem ser usados no case
Case number mod 2 of
0 : ShowMessage(IntToStr(Number)+' mod 2 = 0');
1 : ShowMessage(IntToStr(Number)+' mod 2 = 1');
else ShowMessage(IntToStr(Number)+' mod 2 é desconhecido');
end;
end;
Neste exemplo podemos ver que temos três testes encadeados, onde estamos testando o resto da divisão,
Se é igual a zero;
Se é igual a um;
Se for qualquer outro valor.
Veja como de modo muito fácil, colocamos 3 testes.
Também é possível usar o case com tipos enumerados.
Veja este segundo exemplo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
| // ...
type
TPrimary = (Red, Green, Blue, Yellow);
// ...
// Procedimento para mostrar a cor informada
procedure TForm1.ShowColour(colour : TPrimary);
begin
// Use a case statement to see the colour of the passed var
// Note how important the else clause is, even though we have
// apparently covered all TPrimary values!
Case colour of
Red : ShowMessage('A cor é vermelha');
Green : ShowMessage('A cor é Verde');
Blue : ShowMessage('A cor é Azul');
Yellow : ShowMessage('A cor é Amarela');
else ShowMessage('A cor é desconhecida!');
end;
end;
///....
var
colour : TPrimary;
begin
// Mostrando a cor antes de atribuir o valor
ShowColour(colour);
// Informando a cor
colour := Green;
// mostrando a cor depois de informada
ShowColour(colour)
end |
// ...
type
TPrimary = (Red, Green, Blue, Yellow);
// ...
// Procedimento para mostrar a cor informada
procedure TForm1.ShowColour(colour : TPrimary);
begin
// Use a case statement to see the colour of the passed var
// Note how important the else clause is, even though we have
// apparently covered all TPrimary values!
Case colour of
Red : ShowMessage('A cor é vermelha');
Green : ShowMessage('A cor é Verde');
Blue : ShowMessage('A cor é Azul');
Yellow : ShowMessage('A cor é Amarela');
else ShowMessage('A cor é desconhecida!');
end;
end;
///....
var
colour : TPrimary;
begin
// Mostrando a cor antes de atribuir o valor
ShowColour(colour);
// Informando a cor
colour := Green;
// mostrando a cor depois de informada
ShowColour(colour)
end
Usando um case na definição de um registro (Record)
Também podemos criar um record com atributos definicos conforme um case, sendo este recurso mais avançado para posterior estudo, mas veja o exemplo abaixo
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| // ....
type
// Declare a fruit record using case to choose the
// diameter of a round fruit, or length and height ohterwise.
TFruit = record
name : string[20];
Case isRound : Boolean of // Choose how to map the next section
True :
(diameter : Single); // Maps to same storage as length
False :
(length : Single; // Maps to same storage as diameter
width : Single);
end;
var
apple, banana, fruit : TFruit;
begin
// Set up the apple as round, with appropriate dimensions
apple.name := 'Apple';
apple.isRound := True;
apple.diameter := 3.2;
// Set up the banana as long, with appropriate dimensions
banana.name := 'Banana';
banana.isRound := False;
banana.length := 7.65;
banana.width := 1.3;
// Show the attributes of the apple
fruit := apple;
if fruit.isRound
then ShowMessage(fruit.name +' diameter = '+
FloatToStrF(fruit.diameter, ffFixed, 2, 1)+'"')
else ShowMessage(fruit.name +' length = '+
FloatToStrF(fruit.length, ffFixed, 2, 1)+'" width = '+
FloatToStrF(fruit.width, ffFixed, 2, 1)+'"');
// Show the attributes of the banana
fruit := banana;
if fruit.isRound
then ShowMessage(fruit.name +' diameter = '+
FloatToStrF(fruit.diameter, ffFixed, 2, 1)+'"')
else ShowMessage(fruit.name +' length = '+
FloatToStrF(fruit.length, ffFixed, 2, 1)+'" width = '+
FloatToStrF(fruit.width, ffFixed, 2, 1)+'"');
end;
Fonte
Baseado no post: http://www.delphibasics.co.uk/RTL.asp?Name=Case |
// ....
type
// Declare a fruit record using case to choose the
// diameter of a round fruit, or length and height ohterwise.
TFruit = record
name : string[20];
Case isRound : Boolean of // Choose how to map the next section
True :
(diameter : Single); // Maps to same storage as length
False :
(length : Single; // Maps to same storage as diameter
width : Single);
end;
var
apple, banana, fruit : TFruit;
begin
// Set up the apple as round, with appropriate dimensions
apple.name := 'Apple';
apple.isRound := True;
apple.diameter := 3.2;
// Set up the banana as long, with appropriate dimensions
banana.name := 'Banana';
banana.isRound := False;
banana.length := 7.65;
banana.width := 1.3;
// Show the attributes of the apple
fruit := apple;
if fruit.isRound
then ShowMessage(fruit.name +' diameter = '+
FloatToStrF(fruit.diameter, ffFixed, 2, 1)+'"')
else ShowMessage(fruit.name +' length = '+
FloatToStrF(fruit.length, ffFixed, 2, 1)+'" width = '+
FloatToStrF(fruit.width, ffFixed, 2, 1)+'"');
// Show the attributes of the banana
fruit := banana;
if fruit.isRound
then ShowMessage(fruit.name +' diameter = '+
FloatToStrF(fruit.diameter, ffFixed, 2, 1)+'"')
else ShowMessage(fruit.name +' length = '+
FloatToStrF(fruit.length, ffFixed, 2, 1)+'" width = '+
FloatToStrF(fruit.width, ffFixed, 2, 1)+'"');
end;
Fonte
Baseado no post: http://www.delphibasics.co.uk/RTL.asp?Name=Case
Certo pessoal, espero que tenha ajudado. Dúvidas deixem nos comentários.
Um abraço e até o próximo post! Valeu.
-
Giovani Da Cruz
-
3.834 views
- 0 comentários
- 5 de julho de 2022
Está gostando do conteúdo? Considere pagar um cafezinho para nossa equipe!
Posts Relacionados - Continue Aprendendo