0
|
1 using System;
|
|
2
|
|
3 using NUnit.Framework;
|
|
4
|
|
5 using BLToolkit.Patterns;
|
|
6
|
|
7 namespace HowTo.Patterns
|
|
8 {
|
|
9 //[TestFixture]
|
|
10 public class DuckTyping
|
|
11 {
|
|
12 // By default, all interface methods are optional.
|
|
13 //
|
|
14 public interface OptionalInterface
|
|
15 {
|
|
16 // If the source object does not implement the [b]Method1[/b], a NotImplementedException is thrown at [i]run time[/i].
|
|
17 //
|
|
18 void Method1();
|
|
19
|
|
20 // If the source object does not implement the [b]Method2[/b], a TypeBuilderException is thrown at [i]build time[/i].
|
|
21 //
|
|
22 /*[a]*/[MustImplement]/*[/a]*/
|
|
23 void Method2();
|
|
24
|
|
25 // If the source object does not implement the [b]Method3[/b], an empty stub is genegated.
|
|
26 // The return value and all output parameters will be set to default values.
|
|
27 //
|
|
28 /*[a]*/[MustImplement(false, false)]/*[/a]*/
|
|
29 int Method3();
|
|
30 }
|
|
31
|
|
32 // The MustImplement attribute also can control the entire interface.
|
|
33 //
|
|
34 /*[a]*/[MustImplement]/*[/a]*/
|
|
35 public interface RequiredInterface
|
|
36 {
|
|
37 // If the source object does not implement the [b]Method1[/b], a TypeBuilderException is thrown at [i]build time[/i].
|
|
38 //
|
|
39 void Method1();
|
|
40
|
|
41 // If the source object does not implement the [b]Method2[/b], a NotImplementedException is thrown at [i]run time[/i].
|
|
42 //
|
|
43 /*[a]*/[MustImplement(false)]/*[/a]*/
|
|
44 void Method2();
|
|
45
|
|
46 // If the source object does not implement the [b]Method3[/b], an empty stub is genegated.
|
|
47 // The return value and all output parameters will be set to default values.
|
|
48 //
|
|
49 /*[a]*/[MustImplement(false, false)]/*[/a]*/
|
|
50 int Method3();
|
|
51 }
|
|
52
|
|
53 public class TestClass
|
|
54 {
|
|
55 public int Method3()
|
|
56 {
|
|
57 return 3;
|
|
58 }
|
|
59 }
|
|
60
|
|
61 // Two or more interfaces can be mixed together.
|
|
62 //
|
|
63 public interface InterfaceMix : RequiredInterface, OptionalInterface
|
|
64 {
|
|
65 }
|
|
66
|
|
67 //[Test]
|
|
68 public void Test()
|
|
69 {
|
|
70 InterfaceMix duck = /*[a]*/BLToolkit.Patterns.DuckTyping.Implement/*[/a]*/<InterfaceMix>(new TestClass());
|
|
71 RequiredInterface duck1 = duck;
|
|
72 OptionalInterface duck2 = duck;
|
|
73
|
|
74 duck1.Method1();
|
|
75 duck2.Method1();
|
|
76 }
|
|
77 }
|
|
78 }
|