首页 > 开发 > 综合 > 正文

C# struct class Differences

2024-07-21 02:17:46
字体:
来源:转载
供稿:网友

c# struct/class differences
struct direct{ //...}

class indirect{ //...}
events are locked? exist on stack or heap? can cause garbage collection? meaning of this? always has a default constructor? default construction triggers static construction? can be null? use with the as operator? can be locked? can have a destructor? default field layout? can be a volatile field? can have synchronized methods? can be pointed to? can be stackalloc'd? can be sizeof'd? how to initialize fields? inheritance differences? equals behavior events are locked?
events declared in a class have their += and -= access automatically locked via a lock(this) to make them thread safe (static events are locked on the typeof the class). events declared in a struct do not have their += and -= access automatically locked. a lock(this) for a struct would not work since you can only lock on a reference type expression.
exist on stack or heap?
value type local instances are allocated on the stack. reference type local instances are allocated on the heap.
can cause garbage collection?
creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.
meaning of this?
in a class, this is classified as a value, and thus cannot appear on the left hand side of an assignment, or be used as a ref/out parameter. for example:

class indirect{ //... public void method(indirect that) { refparameter(ref this); // compile-time error outparameter(out this); // compile-time error this = that; // compile-time error } //...}
in a struct, this is classified as an out parameter in a constructor and as a ref parameter in all other function members. thus it is possible to modify the entire structure by assigning to this or passing this as a ref/out parameter. for example:
struct direct{ //... public void reassign(direct that) { refparameter(ref this); // compiles ok outparameter(out this); // compiles ok this = that; // compiles ok } //...}
furthermore, you can reassign a whole struct even when the struct contains readonly fields!
struct direct{ public direct(int value) { field = value; } public void reassign(direct that) { refparameter(ref this); // compiles ok outparameter(out this); // compiles ok this = that; // compiles ok } public readonly int field;}class show{ static void main() { direct s = new direct(42); console.writeline(s.field); // writes 42 s.reassign(new direct(24)); console.writeline(s.field); // writes 24 }}
note however that when you call a method on a readonly value-type field, the method call is made on a copy of the field.
struct direct{ // as above}class caller{ public void method() { console.writeline(d.field); // writes 42 d.reassign(new direct(24)); console.writeline(d.field); // writes 42! } private readonly direct d = new direct(42); }class show{ static void main() { caller c = new caller(); c.method(); }}


always have a default constructor?
a struct always has a built-in public default constructor.

class defaultconstructor{ static void eg() { direct yes = new direct(); // always compiles ok indirect maybe = new indirect(); // compiles if c'tor exists and is accessible //... }}
this means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
class noninstantiable{ private noninstantiable() // ok { }}struct direct{ private direct() // compile-time error { }}


default construction triggers static constructor?
a structs static constructor is not triggered by calling the structs default constructor. it is for a class.

struct direct{ static direct() { console.writeline("this is not written"); }}class nottriggered{ static void main() { direct local = new direct(); }}
can be null?
a struct instance cannot be null.

class nullness{ static void eg(direct s, indirect c) { if (s == null) ... // compile-time error if (c == null) ... // compiles ok }}
use with the as operator?
a struct type cannot be the right hand side operand of the as operator.

class fragment{ static void eg(direct s, indirect c) { direct no = s as direct; // compile-time error indirect yes = c as indirect; // compiles ok //... }}
can be locked?
a struct type expression cannot be the operand of a lock statement.

class lockstatement{ static void eg(direct s, indirect c) { lock(s) { ... } // compile-time error lock(c) { ... } // compiles ok }}
can have a destructor?
a struct cannot have a destructor. a destructor is just an override of object.finalize in disguise, and structs, being value types, are not subject to garabge collection.

struct direct{ ~direct() {} // compile-time error}class indirect{ ~indirect() {} // compiles ok}

and the cil for ~indirect() looks like this:

.method family hidebysig virtual instance void finalize() cil managed{ // ...} // end of method indirect::finalize
default field layout?
the default [structlayout] attribute (which lives in the system.runtime.interopservices namespace) for a struct is layoutkind.sequential whereas the default structlayout for a class is layoutkind.auto. (and yes, despite its name you can tag a class with the structlayout attribute.) in other words the cil for this:

public struct direct{ //...}

looks like this:

.class public sequential ansi sealed beforefieldinit direct extends [mscorlib]system.valuetype{ //...}

whereas the cil for this:

public sealed class indirect{ //...}

looks like this:

.class public auto ansi sealed beforefieldinit indirect extends [mscorlib]system.object{ //...}
can be a volatile field?
you can't declare a user-defined struct type as a volatile field but you can declare a user-defined class type as a volatile field.

class bad{ private volatile direct field; // compile-time error}class good{ private volatile indirect field; // compiles ok}
can have synchronized methods?
you can't use the [methodimpl(methodimploptions.synchronized)] attribute on methods of a struct type (if you call the method you get a runtime typeloadexception) whereas you can use the [methodimpl(methodimploptions.synchronized)] attribute on methods of a class type.

using system.runtime.compilerservices;class indirect{ [methodimpl(methodimploptions.synchronized)] // compiles and runs ok public void method() { //... }}struct direct{ [methodimpl(methodimploptions.synchronized)] // compiles ok, runtime typeloadexception public void method() { //... }}
can be pointed to?
clause 25.2 of the c# standard defines an unmanaged type as any type that isn't a reference type and doesn't contain reference-type fields at any level of nesting. that is, one of the following:
any simple value type (11.1.3, eg byte, int, long, double, bool, etc). any enum type. any pointer type. any user-defined struct-type that contains fields of unmanaged types only. you can never take the address of a instance of a type that is not unmanaged (a fixed variable 25.3).
class bad{ static void main() { indirect variable = new indirect(); unsafe { fixed(indirect * ptr = &variable) // compile-time error { //... } } }}
if you want to fix an unmanaged instance you have to do so by fixing it through an unmanaged field. for example:
class indirect{ public int fixhandle;}class bad{ static void main() { indirect variable = new indirect(); unsafe { fixed(int * ptr = &variable.fixhandle) // compiles ok { //... } } }}
in contrast, you can (nearly) always take the address of an unmanaged instance.
struct direct{ // no reference fields at any level of nesting}class simplecase{ static void main() { direct variable = new direct(); unsafe { direct * ptr = &variable; // compiles ok //... } }}
however, you have to take the address inside a fixed statement if the variable is moveable (subject to relocation by the garbage collector, see 25.3 and example above). also, you can never take the address of a volatile field.


so, in summary, you can never create a pointer to a class type but you sometimes create a pointer to a struct type.
can be stackalloc'd?
you can only use stackalloc on unmanaged types. hence you can never use stackalloc on class types. for example:

class indirect{ //...}class bad{ static void main() { unsafe { indirect * array = stackalloc indirect[42]; // compile-time error //... } }}
where as you can use stackalloc on struct types that are unmanaged. for example:
struct direct{ // no reference fields at any level of nesting}class good{ static void main() { unsafe { direct * array = stackalloc direct[42]; // compiles ok //... } }}


can be sizeof'd?
you can only use sizeof on unmanaged types. hence you can never use sizeof on class types. for example:

class indirect{ //...}class bad{ static void main() { unsafe { int size = sizeof(indirect); // compile-time error //... } }}
where as you can use sizeof on struct types that are unmanaged. for example:
struct direct{ // no reference fields at any level of nesting}class good{ static void main() { unsafe { int size = sizeof(direct); // compiles ok //... } }}


how to initialize fields?
the fields of a class have a default initialization to zero/false/null. the fields of a struct have no default value.

struct direct{ public int field;}class indirect{ public indirect() { } //... public int field;}class defaults{ static void main() { direct s; console.writeline(s.field); // compile-time error indirect c = new indirect(); console.writeline(c.field); // compiles ok }}



you can initialize fields in a class at their point of declaration. for example:

class indirect{ //... private int field = 42; }
you can't do this for fields in a struct. for example:
struct direct{ //... private int field = 42; // compile-time error}
fields in a struct have to be initialized in a constructor. for example:
struct direct{ public direct(int value) { field = value; } //... private int field; // compiles ok}
also, the definite assignment rules of a struct are tracked on an individual field basis. this means you can bypass initialization and "assign" the fields of a struct one a time. for example:
struct direct{ public int x, y;}class example{ static void main() { direct d; d.x = 42; console.writeline(d.x); // compiles ok console.writeline(d.y); // compile-time error }}


inheritance differences?

a struct is implicitly sealed, a class isn't. a struct can't be abstract, a class can. a struct can't call : base() in its constructor whereas a class with no explicit base class can. a struct can't extend another class, a class can. a struct can't declare protected members (eg fields, nested types) a class can. a struct can't declare abstract function members, an abstract class can. a struct can't declare virtual function members, a class can. a struct can't declare sealed function members, a class can. a struct can't declare override function members, a class can. the one exception to this rule is that a struct can override the virtual methods of system.object, viz, equals(), and gethashcode(), and tostring().

equals behavior?
classes inherit object.equals which implements identity equality whereas structs inherit valuetype.equals which implements value equality.

using system.diagnostics;struct direct{ public direct(int value) { field = value; } private int field;}class indirect{ public indirect(int value) { field = value; } private int field;}class equalsbehavior{ static void main() { direct s1 = new direct(42); direct s2 = new direct(42); indirect c1 = new indirect(42); indirect c2 = new indirect(42); bool structequality = s1.equals(s2); bool classidentity = !c1.equals(c2); debug.assert(structequality); debug.assert(classidentity); }}
overriding equals for structs should be faster because it can avoid reflection and boxing.
struct direct{ public direct(int value) { field = value; } public override bool equals(object other) { return other is direct && equals((direct)other); } public static bool operator==(direct lhs, direct rhs) { return lhs.equals(rhs); } //... private bool equals(direct other) { return field = other.field; } private int field;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表