【发布时间】:2015-03-14 11:48:25
【问题描述】:
好的。我设法将所有内容压缩为 2 个问题:
1/ 公共枚举应该在类内还是类外?我认为它们都有效,但有什么好的做法吗?
2/ 我不明白如何设置一个包含另一个类的对象的构造函数。请参阅底部“主要”类的评论。
GSM 类:
using System.Text;
class GSM
{
public string model;
public string manufacturer;
public decimal price;
public string owner;
Battery battery = new Battery("Nokia", 7, 5);
Display display = new Display(12.5, 3);
// CONSTRUCTORS:
public GSM(string model, string manufacturer, decimal price, string owner)
{
this.model = model;
this.manufacturer = manufacturer;
this.price = price;
this.owner = owner;
}
public GSM(string model, string manufacturer, decimal price, string owner, Battery battery, Display display)
: this(model, manufacturer, price, owner)
{
this.battery = battery;
this.display = display;
}
}
电池
public enum BatteryType // Is this suppose to be here or inside the class?
{
LiIon, LiPo, NiMH, NiCd
}
class Battery
{
//battery characteristics
private string model;
private int hoursIdle;
private int hoursTalk;
private BatteryType batteryType = new BatteryType();
}
====== 显示
class Display
{
//display characteristics
private double size;
private int numberOfColors;
// CONSTRUCTORS:
public Display(double size, int numberOfColors)
{
this.size = size;
this.numberOfColors = numberOfColors;
}
}
====主要:
class GSMTest
{
public static void Main()
{
GSM myGSM = new GSM("Sony ERcs", "Sony ERRR", 124.56m, "Pesho", BatteryType.LiPo, 12.3);
// I can't create this object. Argument5: cannont convert from GSM.BatteryType to GSM.Battery. What gives!?
// Display has 2 fields. I have an instance of it in GSM. Yet I don't know how to set it here so I can create myGSM
}
}
附:它们都来自同一个命名空间;还有一个 Battery 类的构造函数。忘记加了,不知道有没有必要。
【问题讨论】:
-
我们不会分析您的完整代码。创建一个小样本来重现您遇到的问题,并针对每个问题在一个问题中描述问题,分享您针对该特定问题的研究。
-
谢谢!我处理好了。
-
您的 GSM 构造函数需要一个 Battery 类的实例,而不是 BatteryType 类型的枚举。您应该创建一个 Battery 实例并在构造函数调用中传递对该实例的引用。 Display 参数也是如此。你需要一个 Display 的实例来传递,而不是一个浮点数
-
我在主类中添加了 Battery 和 Display 实例,它工作正常。但是我已经在 GSM 课程中使用了它们。我希望他们从那里开始工作。所以我可以保持主要的干净和简单。
-
知道了!我必须在 GSM 构造函数中启动新对象 Battery 和 Display。虽然这对我来说有点晦涩和疯狂。新对象作为构造函数中的参数!?