我正在学习访问器方法和枚举。我在'车辆'命名空间下编写了一个公共类'Car',并设置了_manufacturer,_model,_year和_color等私有属性。我想编写一个方法来访问属性,另一个方法来设置/更新它们。这是我的课:为私有对象属性创建一个访问器方法 - 枚举?
using System;
namespace Vehicles
{
public class Car
{
private string _manufacturer;
private string _model;
private string _year;
private string _color;
public void honkHorn()
{
// Add argument for a file name?
// Code here to play a WAV file?
MessageBox.Show("Honk!");
}
public string getCarInfo(string whichProperty)
{
switch (whichProperty)
{
case ("manufacturer"):
return _manufacturer;
case ("model"):
return _model;
case ("year"):
return _year;
case ("color"):
return _color;
default:
return null;
}
}
public void setCarInfo(string whichProperty, string newValue)
{
switch (whichProperty)
{
case ("manufacturer"):
_manufacturer = newValue;
break;
case ("model"):
_model = newValue;
break;
case ("year"):
_year = newValue;
break;
case ("color"):
_color = newValue;
break;
}
}
}
}
这是我的表格:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Vehicles;
namespace CS_Enumeration
{
public partial class Form1 : Form
{
public Car myCar = new Car();
public Form1()
{
InitializeComponent();
myCar.setCarInfo("manufacturer", "Ford");
labelManfValue.Text = myCar.getCarInfo("manufacturer");
myCar.setCarInfo("model", "Ranger");
labelModelValue.Text = myCar.getCarInfo("model");
myCar.setCarInfo("year", "2012");
labelYearValue.Text = myCar.getCarInfo("year");
myCar.setCarInfo("color", "Blue");
labelColorValue.Text = myCar.getCarInfo("color");
}
private void button1_Click(object sender, EventArgs e)
{
myCar.honkHorn();
}
}
}
这真的是编写能获取/设置一个方法的最佳方法是什么?我首先尝试转换一个匹配对象属性名称的字符串值并返回实际属性,但这不起作用(除非有人知道如何将字符串转换为对象属性?)。
感谢您的回复。这是我正在阅读的一本书的练习。它甚至说并非所有事情都应该公开,但并非所有事情都应该是私有的。那么我怎么知道什么时候应该/不应该公开/私下?听起来这本书引导我错误地指出什么是好的编码设计。任何人有任何书籍建议,学习Visual C#良好的编码设计实践?
你为什么要这样做?伊莫这是一个可怕的设计 - 只是暴露属性。最重要的是,您在当前方法中丢失了所有类型的安全性,任何错字都会导致运行时异常 – BrokenGlass 2012-03-02 02:01:40
请参阅编辑原始文章。这些都是基于我正在阅读的C#书籍,建议使用私有变量。我可以从我必须经历的get/set属性中看出它有点荒谬。谢谢。 – spickles 2012-03-02 03:10:46
这是什么书?我们想忽略它,并可能嘲笑它。 – 2012-03-02 04:51:01