结构和类的构造函数之间的区别 [英] Difference between the constructors of a struct and class

查看:143
本文介绍了结构和类的构造函数之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试为没有粗体位的结构/结构键入所有这些内容时,我得到了混乱的错误行.为什么当我在代码中添加:this()时,弯曲的线条消失了?对于类,不会出现此错误,但对于结构,则会出现此错误.

When I try to type all this out for a struct/structure without the bits in bold, I am getting squiggly error lines. Why is it that when I add the :this() to the code, the squiggly lines disappear? This error doesn''t appear for classes but they will for structs.

 struct Line
    {
        private Point point1 { get; set; }
        private Point point2 { get; set; }

        readonly double Length;
        readonly double Slope;

        public Line(Point p1, Point p2):this()
        {
            point1 = p1;
            point2 = p2;
        }
}

推荐答案

结构不能具有统一的成员.
类可以.

结构还具有由编译器添加的默认构造函数,因此当您添加:this()作为默认构造函数调用时,会出现错误消息,提示结构不能具有
未初始化的成员Disapper作为默认构造函数将为成员分配默认值.

当您更改课程时,因为他们可以拥有这样的成员,所以错误也会消失.
Structures cannot have unitialized members.
Classes can.

Structures also have default constructor added by compiler so when you adding :this() as default constructor call, error with message that struct cannot have
uninitialized members disapper as default constructor will assign default values to members.

When you change to class, as they can have such members, error will also disappear.


这篇关于结构和类的构造函数之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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