| [ directory ] |
|
6.2 Class membersIn addition to instance and static variables, other classes (inner classes), and methods, a C# class can include many other different members. Class members can be divided into two categories:
Members that can contain executable code are known as function members of the class. Like JavaAll methods and variables must be declared within a class. [2] The only C# statements that can be outside a class's curly braces are:
Unlike JavaThere are several new class members not heard of in Java. Examples include properties, events, indexers, operators, delegates, destructors, and static constructors. Table 6.2 gives a brief description of C# class members. Note the new members which do not have equivalents in Java. The following C# class contains all the possible members mentioned above: [3]
1: using System;
2:
3: public class MyClass{
4:
5: // constant
6: public const string MyConstant = "C Sharp is fun!";
7:
8: // instance field
9: public int MyField = 2;
10:
11: // another instance field
12: private string[] MyArray = new string[10];
13:
14: // instance constructor
15: public MyClass(){
16: Console.WriteLine("1st instance constructor running");
17: }
18:
19: // overloaded instance constructor
20: public MyClass(int newMyField){
21: Console.WriteLine("2nd instance constructor running");
22: MyField = newMyField;
23: }
24:
25: // static constructor
26: static MyClass(){
27: Console.WriteLine("static constructor running");
28: }
29:
30: // destructor
31: ~MyClass(){
32: Console.WriteLine("destructor running");
33: }
34:
35: // instance method
36: public void DoSomething(){
37: Console.WriteLine("instance method running");
38: }
39:
40: // static Main method
41: public static void Main(){
42: Console.WriteLine("Main method running");
43: MyClass mc = new MyClass();
44: mc = null;
45: }
46:
47: // property
48: public int MyProperty{
49: get{
50: return MyField;
51: }
52: set{
53: MyField = value;
54: }
55: }
56:
57: // indexer
58: public string this [int index]{
59: get{
60: return MyArray[index];
61: }
62: set{
63: MyArray[index] = value;
64: }
65: }
66:
67: // event
68: public event EventHandler MyEvent;
69:
70: // operator method
71: public static MyClass operator + (MyClass a, MyClass b){
72: return new MyClass(a.MyField + b.MyField);
73: }
74:
75: // nested class
76: class MyNestedClass{
77: }
78: } // end class
| |||||||||||||||||||||||||||||||||||||||||||||
| [ directory ] |
|