A lot of times the answer is merely when I want things to be allocated on a stack instead of the heap.. assuming I dont know what the stack and the heap are (and please dont try to explain it here), when exactly should I be using structs instead of classes?
Here is the answer I've been giving out, but please tell me if I'm wrong or falling short of a better answer:
I create structs usually when I have enums that I want to add more data to. For instance, I might start with a simple enum:
public enum Colors { Blue, Green, Red }
Run Code Online (Sandbox Code Playgroud)
Then if I need to store more aspects of this data I go to structs:
public struct Color
{
string Name;
int HexValue;
string Description;
}
public class Colors
{
public static Color Blue;
public static Color Red;
public static Color Green;
static Colors()
{
Blue = new Color("Blue", 1234, "A light blue"
}
}
Run Code Online (Sandbox Code Playgroud)
重点是......类似于枚举,我只是在想要声明一堆类型时使用结构.
使用结构的实际时间是你想要像属性这样的值类型.值类型与引用类型的行为有很大不同,如果您不了解,则差异可能会令人震惊并导致错误.例如,将结构复制到(和退出)方法调用中.
堆栈与堆栈对我来说不是一个令人信服的论据.在典型的.NET应用程序中,您经常关心对象的位置?
我很少在.NET应用程序中使用结构.我真正使用它们的唯一地方是在一个游戏中,我想要值类型,如矢量等对象的属性.
这是一个更简单的问题.C++中的结构和类彼此相同,只有一个小的区别.默认情况下,C++结构中的所有内容都是公共的,因为默认情况下,C++类中的所有内容都是私有的.这是唯一的区别.
| 归档时间: |
|
| 查看次数: |
298 次 |
| 最近记录: |