Conditional-Attribut
A01.cs
#define tracing
using System;
using System.Diagnostics;
class Trace {
[Conditional("tracing")]
public static void WriteLine(string s) {
Console.WriteLine(s);
}
[Conditional("tracing")]
public static void WriteLine() {
Console.WriteLine();
}
[Conditional("tracing")]
public static void Write(string s) {
Console.Write(s);
}
}
class Stack {
int[] data = new int[16];
int top = 0;
[Conditional("tracing")]
void Dump() {
for (int i = 0; i < top; i++)
Console.Write(data[i] + " ");
Console.WriteLine();
}
public void Push(int x) {
Trace.Write("Push(" + x + "): ");
if (top < 16) {
data[top] = x; top++;
} else throw new OverflowException();
Dump();
}
public int Pop() {
Trace.Write("Pop(): ");
if (top == 0) throw new UnderflowException();
top--;
Dump();
return data[top];
}
public int Size {
get { return top; }
}
}
class OverflowException: ApplicationException {}
class UnderflowException: ApplicationException {}
public class Test {
public static void Main() {
Stack stack = new Stack();
for (int i = 0; i < 5; i++)
stack.Push(i);
while (stack.Size > 1) {
stack.Push(stack.Pop() + stack.Pop());
}
Console.WriteLine("result = " + stack.Pop());
}
}
|
Ist das Symbol "tracing" wie hier definiert, erzeugt das Programm folgende
Ausgabe.
Push(0): 0
Push(1): 0 1
Push(2): 0 1 2
Push(3): 0 1 2 3
Push(4): 0 1 2 3 4
Pop(): 0 1 2 3
Pop(): 0 1 2
Push(7): 0 1 2 7
Pop(): 0 1 2
Pop(): 0 1
Push(9): 0 1 9
Pop(): 0 1
Pop(): 0
Push(10): 0 10
Pop(): 0
Pop():
Push(10): 10
Pop():
result = 10
|