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
红圈出来的代码应该使用变量 value,可以对照课程源码或视频检查一下。
112022-05-10
相似问题
为什么加上ref以后,数值就可以交换了?
回答 1
属性
回答 1