建立一个C#定义宝马品牌(BMW)类,应当:
BMW有几个私有属性:型号(type)名称(Name),价格(price)
对属性进行封装
然后为构造函数进行重载,提供为1、2、3个属性赋值,一个都不赋值
定义方法show(),该方法负责输出宝马所有基本信息;
在Main中测试,要求每个构造函数的情况都要测试到
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public class BMWClass {
private string type;
/// <summary>
/// 封装type
/// </summary>
public string Type { get { return type; } set { type = value; } }
private string name;
/// <summary>
/// 封装name
/// </summary>
public string Name { get { return name; } set { name = value; } }
private string price;
/// <summary>
/// 封装price
/// </summary>
public string Price { get { return price; } set { price = value; } }
/// <summary>
/// 一个都不赋值
/// </summary>
public BMWClass() { }
/// <summary>
/// 赋值一个
/// </summary>
/// <param name="_type"></param>
public BMWClass(string _type) {
type = _type;
}
/// <summary>
/// 赋值两个
/// </summary>
/// <param name="_type"></param>
/// <param name="_name"></param>
public BMWClass(string _type, string _name) {
type = _type;
name = _name;
}
/// <summary>
/// 赋值三个
/// </summary>
/// <param name="_type"></param>
/// <param name="_name"></param>
/// <param name="_price"></param>
public BMWClass(string _type, string _name, string _price) {
type = _type;
name = _name;
price = _price;
}
/// <summary>
/// 输出所有信息
/// </summary>
public void show() {
Console.WriteLine("type = " + type + " name = " + name + " price =" + price);
}
}
static void Main(string[] args)
{
BMWClass bMW = new BMWClass();
bMW.Type = "1";
bMW.Name = "X1";
bMW.Price = "10万";
bMW.show();
BMWClass bMW1 = new BMWClass("2");
bMW1.Name = "X2";
bMW1.Price = "20万";
bMW1.show();
BMWClass bMW2 = new BMWClass("3", "X3");
bMW2.Price = "30万";
bMW2.show();
BMWClass bMW3 = new BMWClass("4", "X4","40万");
bMW3.show();
}
如果我没理解错的话 应该是这个意思
做了一点升级:
internal class Program
{
static void Main(string[] args)
{
BMW_Model model1 = new BMW_Model();
BMW_Model mode2 = new BMW_Model("名称");
BMW_Model model3 = new BMW_Model("名称", "方式", 28000);
BMW_Model model4 = new BMW_Model(type: "方式");
}
}
public class BMW_Model
{
#region 方式一
public string Name { get; set; }
#endregion
#region 方式二
private string _type;
//public string Type { get { return _type; } } // 只读
public string Type { get { return _type; } set { _type = value; } } // 可读可写
#endregion
#region 方式三
private decimal _price;
//public decimal Price { get => _price; }
public decimal Price { get => _price; set => _price = value; }
#endregion
public BMW_Model(string name = null, string type = null, decimal? price = null)
{
this.Name = name ?? string.Empty;
this._type = type ?? string.Empty;
this._price = price ?? 0;
}
}