I l @ ve RuBoard |
As previously stated, IL is not an OO language in itself. For IL to support multiple source languages and constructs, IL supports the notion of creating classes and creating instances of classes. Looking at the IL for declaring and creating classes will give you a better understanding of the Common Language Specification (CLS). Listing 1.3.3 shows the IL code for creating and using a class. Listing 1.3.3 Creating a Class in IL1: .assembly class_test as "class_test" 2: { 3: .ver 1:0:0:0 4: } 5: 6: 7: .module class_test.exe 8: 9: 10: //Create a class Dog with two public fields 11: 12: .class public auto ansi Dog extends [mscorlib]System.Object { 13: 14: //public data fields 15: .field public class System.String m_Name 16: .field public int32 m_Age 17: 18: 19: //Create a method to display the fields 20: .method public hidebysig instance void Print() il managed 21: { 22: .maxstack 8 23: ldstr "Name : { 0} \ nAge :{ 1} " 24: ldarg.0 25: ldfld class System.String Dog::m_Name 26: ldarg.0 27: ldfld int32 Dog::m_Age 28: box [mscorlib]System.Int32 29: call void [mscorlib]System.Console::WriteLine(class System.String, 30: class System.Object, 31: class System.Object) 32: ret 33: } 34: 35: //The Constructor 36: .method public hidebysig specialname rtspecialname instance void .ctor() il managed 37: { 38: .maxstack 8 39: ldarg.0 40: call instance void [mscorlib]System.Object::.ctor() 41: ret 42: } 43: 44: } 45: 46: .method public static void Main() il managed 47: { 48: .entrypoint 49: 50: .maxstack 2 51: 52: .locals (class Dog V_0) 53: 54: newobj instance void Dog::.ctor() 55: stloc.0 56: ldloc.0 57: ldstr "Daisy" 58: stfld class System.String Dog::m_Name 59: ldloc.0 60: ldc.i4.3 61: stfld int32 Dog::m_Age 62: ldloc.0 63: call instance void Dog::Print() 64: ret 65: } 66: Creating a class in IL is a fairly straightforward process. The Dog class declared in Listing 1.3.3 derives from the System.Object class, which is the base class of all .NET classes. In .NET, data members are known as fields and as such are marked with the .field keyword. To define a class method, all that is required is to define the method within the scope of the class to which the method belongs. The Print method is declared on line 20 of Listing 1.3.3. Notice the instance method modifier that is applied to the Print method. For the Print method to be invoked, an instance of the Dog class is required. The same is true for the constructor of the Dog class. IL provides two modifiers that must be applied to instance constructors. The rtspecialname modifier is used by the runtime, whereas the specialname is provided for various .NET tools, such as Visual Studio .NET. |
I l @ ve RuBoard |