inheritance - Can a structure inherit from a class in .NET? -
i confused inheritance in .net , here why.
i of understanding structure cannot inherit class in .net, example, following won't compile:
struct mystruct : myclass { }
but today read integers (and other value types) structs , not objects , inherit valuetype class. valuetype class inherits system.object , purpose override methods in system.object make these methods suitable value types.
so what's deal? can structure inherit class in .net, can not or can in circumstances?
thanks
within guts of .net, definition struct containing members same definition class same fields , members, , inherits system.valuetype
. note compilers not allow 1 declare class
inherits valuetype
, when 1 declares struct
, compiler, "behind scenes" declares class does.
what makes value types special in .net way run-time allocates storage locations (variables, fields, parameters, etc.) when storage location of type not inheriting valuetype
declared, runtime allocate space heap object reference. contrast, when storage location of type inheriting valuetype
declared, runtime allocate space public , private fields of type. type int
, system allocates private field of special primitive type, outside normal type system.
note storage location of value type doesn't hold instance of type; instead is instance of type, , holds of fields of type. statement struct1 = struct2
not replace value-type instance struct1
instance struct2
. instead, copies of fields struct2
on corresponding fields in struct1
. likewise if value-type storage location passed method procedure without using ref
keyword, passed not struct instance itself, rather contents of fields.
if necessary copy value-type storage location 1 of type not derived valuetype
(e.g. object
or icomparable
), system create new heap-object instance of value type, copy fields value type new instancen , store reference new instance in target storage location. process called "boxing". compilers implicitly, attempting behave though value type storage location holds object derives valuetype
. it's important note, though, illusion. if type x
derives y
, 1 has x
named xx
, y
named yy
, , 1 performs xx = yy
, such statement should cause xx
, yy
refer same object instance. happen if xx
, yy
types not derived valuetype
, if yy
holds instance of derived valuetype
. not happen, however, if xx
and/or yy
derives valuetype
. in case, system copy fields 1 instance (possibly new) instance.
Comments
Post a Comment