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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
using System;
interface IncrDecr
{
void Incr(int a);
void Decr(int a);
int Val();
}
class MyInt : IncrDecr
{
int x;
public void Incr(int a) { x += a; }
public void Decr(int a) { x -= a; }
public int Val() { return x; }
}
class MyCounter<T> where T : IncrDecr, new()
{
T counter = new T();
T[] counters = new T[1];
public void Increment()
{
counter.Incr(100);
}
public void Decrement()
{
counter.Decr(100);
}
public void Increment(int index)
{
counters[index] = new T();
counters[index].Incr(100);
}
public void Decrement(int index)
{
counters[index].Decr(100);
}
public virtual void Increment2(T cnter)
{
cnter.Incr(100);
counter = cnter;
}
public virtual void Decrement2(T cnter)
{
cnter.Decr(100);
counter = cnter;
}
public int Val()
{
return counter.Val();
}
public int Val(int index)
{
return counters[index].Val();
}
}
class test
{
public static int Main()
{
MyCounter<MyInt> mc = new MyCounter<MyInt>();
mc.Increment();
if (mc.Val() != 100)
{
Console.WriteLine("FAILED 1");
Console.WriteLine("Expected: 100, Actual: {0}", mc.Val());
return 1;
}
mc.Decrement();
if (mc.Val() != 0)
{
Console.WriteLine("FAILED 2");
Console.WriteLine("Expected: 0, Actual: {0}", mc.Val());
return 2;
}
mc.Increment(0);
if (mc.Val(0) != 100)
{
Console.WriteLine("FAILED 3");
Console.WriteLine("Expected: 100, Actual: {0}", mc.Val(0));
return 3;
}
mc.Decrement(0);
if (mc.Val(0) != 0)
{
Console.WriteLine("FAILED 4");
Console.WriteLine("Expected: 0, Actual: {0}", mc.Val(0));
return 4;
}
MyInt mi = new MyInt();
mc.Increment2(mi);
if (mc.Val() != 100)
{
Console.WriteLine("FAILED 5");
Console.WriteLine("Expected: 100, Actual: {0}", mc.Val());
return 5;
}
mc.Decrement2(mi);
if (mc.Val() != 0)
{
Console.WriteLine("FAILED 6");
Console.WriteLine("Expected: 0, Actual: {0}", mc.Val());
return 6;
}
Console.WriteLine("PASSED");
return 100;
}
}
|