What is a Value Class and what is a reference Class in C#?

后端 未结 7 2035
刺人心
刺人心 2020-12-11 17:44

What is the definition of a value class and reference class in C#?

How does this differ from a value type and reference

7条回答
  •  独厮守ぢ
    2020-12-11 17:52

    You may be thinking of C++/CLI which, unlike C#, allows the user to declare a "value class" or a "ref class." In C#, any class you declare will implicitly be a reference class - only built-in types, structs, and enums have value semantics. To read about value class in C++/CLI, look here: http://www.ddj.com/cpp/184401955

    Value classes have very little functionality compared to ref classes, and are useful for "plain old data"; that is, data which has no identity. Since you're copying the data when you assign one to another, the system provides you with a default (and mandatory) copy constructor which simply copies the data over to the other object.

    To convert a value class into a reference class (thereby putting it on the garbage-collected heap) you can "box" it.

    To decide whether a class you are writing is one or the other, ask yourself whether it has an identity. That usually means that it has some state, or has an identifier or a name, or a notion of its own context (for example a node pointing to nearby nodes).

    If it doesn't, it's probably a value class.

    In C#, however, value classes are declared as "structs".

提交回复
热议问题