Orice este un obiect


using System;

namespace Namespace
{
public interface IObject
{
void MyToString();
}
public class MyObject : IObject
{
public void MyToString(){}
}
public class Program
{
static void SomeFunction(object a, object b, IObject c, MyObject d)
{
Int32 i = (int)a;
MyObject obj_b = b as MyObject;
MyObject obj_bb = (MyObject)b;
IObject iobj_b = (IObject)b;

MyObject obj_c = (MyObject)c;
MyObject obj_cc = c as MyObject;

IObject iobj_d = d as MyObject;
IObject iobj_dd = d;
IObject iobj_ddd = (MyObject)d;
}
static void Main(string[] args)
{
Int32 i = 3;
MyObject myobj = new MyObject();

SomeFunction(i, myobj, myobj, myobj);
}
}
}

Clasa de baza a fiecarei instante este System.Object. Orice instanta a clasei System.Object este capabila sa referentieze orice alta instanta a unei clase.
Mecanismul insa difera de la caz la caz si se poate observa foarte bine in codul IL:

.method private hidebysig static void SomeFunction(object a,
object b,
class Namespace.IObject c,
class Namespace.MyObject d) cil managed
{
// Code size 55 (0x37)
.maxstack 1
.locals init ([0] int32 i,
[1] class Namespace.MyObject obj_b,
[2] class Namespace.MyObject obj_bb,
[3] class Namespace.IObject iobj_b,
[4] class Namespace.MyObject obj_c,
[5] class Namespace.MyObject obj_cc,
[6] class Namespace.IObject iobj_d,
[7] class Namespace.IObject iobj_dd,
[8] class Namespace.IObject iobj_ddd)
//000019: {
IL_0000: nop
//000020: Int32 i = (int)a;
IL_0001: ldarg.0
IL_0002: unbox.any [mscorlib]System.Int32
IL_0007: stloc.0
//000021: MyObject obj_b = b as MyObject;
IL_0008: ldarg.1
IL_0009: isinst Namespace.MyObject
IL_000e: stloc.1
//000022: MyObject obj_bb = (MyObject)b;
IL_000f: ldarg.1
IL_0010: castclass Namespace.MyObject
IL_0015: stloc.2
//000023: IObject iobj_b = (IObject)b;
IL_0016: ldarg.1
IL_0017: castclass Namespace.IObject
IL_001c: stloc.3
//000024:
//000025: MyObject obj_c = (MyObject)c;
IL_001d: ldarg.2
IL_001e: castclass Namespace.MyObject
IL_0023: stloc.s obj_c
//000026: MyObject obj_cc = c as MyObject;
IL_0025: ldarg.2
IL_0026: isinst Namespace.MyObject
IL_002b: stloc.s obj_cc
//000027:
//000028: IObject iobj_d = d as MyObject;
IL_002d: ldarg.3
IL_002e: stloc.s iobj_d
//000029: IObject iobj_dd = d;
IL_0030: ldarg.3
IL_0031: stloc.s iobj_dd
//000030: IObject iobj_ddd = (MyObject)d;
IL_0033: ldarg.3
IL_0034: stloc.s iobj_ddd
//000031: }
IL_0036: ret
} // end of method Program::SomeFunction


Comments

Popular posts from this blog

IIS 7.5, HTTPS Bindings and ERR_CONNECTION_RESET

Table Per Hierarchy Inheritance with Column Discriminator and Associations used in Derived Entity Types

Verify ILogger calls with Moq.ILogger