Guide to the Language
Struct Field Initializers
Download 2 Mb. Pdf ko'rish
|
C sharp
- Bu sahifa navigatsiya:
- Struct Inheritance
- Struct Guideline
Struct Field Initializers
Fields within a struct cannot be given initial values, unless they are declared as const or static. struct Point { public int x = 1, y = 1; // compile-time error public static int myStatic = 5; // allowed public const int myConst = 10; // allowed } Struct Inheritance A struct cannot inherit from another struct or class, and it cannot be a base class. This also means that struct members cannot be declared as protected, private protected, or protected internal, and that struct methods cannot be marked as virtual. Structs implicitly inherit from System.ValueType, which in turn inherits from System.Object. Although structs do not support user-defined inheritance, they can implement interfaces in the same way as classes. Chapter 24 StruCt 140 Struct Guideline The struct type is typically used to represent lightweight classes that encapsulate small groups of related variables. The primary reason for using a struct instead of a class is to get value type semantics. For example, the simple types are in fact all struct types. For these types, it is more natural that assignment copies the value rather than the reference. Structs can also be useful for performance reasons. A struct is more efficient than a class in terms of memory. It not only takes up less memory than a class, but it also does not need memory to be allocated for it as required by reference type objects. Furthermore, a class requires two memory spaces, one for the variable and one for the object, whereas a struct only needs one. This can make a significant difference for a program that operates on a great number of data structures. Bear in mind that assignment and parameter passing by value are typically more expensive with structs than with reference types, because the entire struct needs to be copied for such operations. Chapter 24 StruCt 141 © Mikael Olsson 2020 M. Olsson, C# 8 Quick Syntax Reference, https://doi.org/10.1007/978-1-4842-5577-3_25 Download 2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling