set 传值不成功?

来源:3-9 【操作】const、readonly与writeonly

慕移动1501610

2022-05-08

;
我先创建坐标点x,y,然后永set还改变x的值,但是发现改变不了x的值。而且在get传入-10也不报错。

结果不报错,图片描述

using System;
using System.Collections.Generic
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _06_C类的封装
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Point a = new Point(55,99);

            a.ShowPoint();
            
            a.X = -10;
            a.X = 10;
            a.Y = -20;

            a.ShowPoint();


            Console.WriteLine($"x:{a.X},y:{a.Y}");
            Console.ReadKey();
        }


        public class Point
        {
            private int _x;
            private int _y;

            public Point()  //重构方法 / 和类的名称一样,但是传参不一样
            {
                this._x = 0;
                this._y = 0;
            }

            public Point(int x, int y)  //重构方法 / 和类的名称一样,但是传参不一样
            {
                this._x = x;
                this._y = y;
            }


            public int X { 
                            get { return this._x; }
                            set
                            {
                                if (X < 0)
                                {
                                    throw new Exception("X的值不能小于0");
                                }
                                this._x = X;
                                Console.WriteLine($"现在X的值是 {this._x},{X}");
                            }
                        }
            public int Y  {
                            get { return this._y; }
                            set
                            {
                                if (Y < 0)
                                {
                                    throw new Exception("Y的值不能小于0");
                                }
                                this._y = Y;
                                Console.WriteLine($"现在Y的值是 {this._y},{Y}");
                            }
                        }

            public void ShowPoint()
            {
                Console.WriteLine($"坐标x是{this._x},坐标y是{this._y}");
                Console.ReadKey();
            }
           
        }
    }
}

在这里输入代码
写回答

1回答

阿莱克斯刘

2022-05-10

https://img.mukewang.com/szimg/6279ef0c0934263b13941232.jpg


红圈出来的代码应该使用变量 value,可以对照课程源码或视频检查一下。

1
1
慕移动1501610
已经解决了,是因为我用的框架不是Core。现在解决了,谢啦
2022-05-10
共1条回复

C#速成指南--从入门到进阶,实战WPF与Unity3D开发

系统掌握C#核心和应用,获得全行业适配的技能

839 学习 · 198 问题

查看课程