C#为什么要结构体,如果类可以覆盖吗? [英] C# why need struct if class can cover it?

查看:306
本文介绍了C#为什么要结构体,如果类可以覆盖吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道为什么我们需要结构体类,如果能做到所有结构可以多? 。把值类型的类没有副作用,我觉得

Just wondering why we need struct if class can do all struct can and more? put value types in class has no side effect, I think.

编辑:无法看到使用结构的充分理由。

cannot see any strong reasons to use struct

一个结构是相似的一类,具有以下主要区别:

A struct is similar to a class, with the following key differences:


  • 系统结构是值类型,而
    类是引用类型。

  • 系统结构不支持继承
    (除从
    对象隐含派生)。

  • 系统结构可以将所有成员
    类即可,除了以下内容:

  • 参数的构造函数

  • 终结

  • 虚拟成员

  • A struct is a value type, whereas a class is a reference type.
  • A struct does not support inheritance (other than implicitly deriving from object).
  • A struct can have all the members a class can, except the following:
  • A parameterless constructor
  • A finalizer
  • Virtual members

一个结构是用来代替一个类时,值类型的语义是可取的。结构典型的例子有数字类型,它是更自然的分配复制值,而不是一个参考。由于结构是值类型,每个实例并不需要在堆上的对象实例化。创建一个类型的多个实例时,这是非常重要的。

A struct is used instead of a class when value type semantics are desirable. Good examples of structs are numeric types, where it is more natural for assignment to copy a value rather than a reference. Because a struct is a value type, each instance does not require instantiation of an object on the heap. This can be important when creating many instances of a type.

推荐答案

自定义值类型都没有的绝对必要 - Java那样没有他们,例如。然而,他们仍然是有用的。

Custom value types aren't absolutely necessary - Java does without them, for example. However, they can still be useful.

例如,在野田佳彦时间我们使用他们相当广泛,作为代表之类的东西的瞬间,而不涉及对象的开销的有效方法。

For example, in Noda Time we're using them pretty extensively, as an efficient way of representing things like instants without the overhead of an object being involved.

我不会说类可以做的所有结构可以更多。 - 他们的行为有所不同,并且应该被认为是不同的。

I wouldn't say that "class can do all struct can and more" - they behave differently, and should be thought of differently.

这篇关于C#为什么要结构体,如果类可以覆盖吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆