我正在学习 C# 并学习类,我有一个关于类初始化和构造函数的最佳实践的问题。
例如,我正在根据 C# 玩家指南进行练习,这就是我最终得到的代码:
internal class Arrows
{
/// <summary>
/// Basic Practice class to ask for and define details of an arrow
/// </summary>
private enum _arrowhead
{
// Type of arrowhead
Steel,
Wood,
Obsidian,
}
private enum _fletching
{
// Type of fletching
Plastic,
TurkeyFeathers,
GooseFeathers,
}
private int _shaftLength = 60; // default length of arrows is 60cm
private float _shaftCostPerCm = 0.05f;
private float _costOfArrow;
public Arrows() {
Console.WriteLine("Hello dear customer");
Console.WriteLine("Welcome to my arrow shop\n");
Console.WriteLine("First things first, what type of arrowhead would you like");
foreach (string head in Enum.GetNames(typeof(_arrowhead))){
Console.WriteLine(head + " = " + getHeadPrices(head) + " gold");
}
string _Head = Console.ReadLine();
Console.WriteLine("\nTime now to select the type of fletching");
foreach (string fletch in Enum.GetNames(typeof(_fletching)))
{
Console.WriteLine(fletch + " = " + getFletchingPrices(fletch) + " gold");
}
string _fletchingType = Console.ReadLine();
Console.WriteLine("\nHow long do you want the arrows to be?");
Console.WriteLine("I can manage to make arrows between 60 and 100 cm");
_shaftLength = Convert.ToInt32(Console.ReadLine());
_costOfArrow = singleArrowCost(_Head, _fletchingType, _shaftLength, _shaftCostPerCm);
Console.WriteLine($"\nThe cost of one of these arrows is {_costOfArrow}");
}
我只是想知道更好的做法是在类之外编写并提示用户所有这些内容,然后在构造函数中传递参数,或者将所有这些语句传递到构造函数内部的控制台并相应地分配值是否可以。
一定要在类之外获取所有输入,并将其作为参数传递。这就是关注点分离的原则。
构造函数应该仅用于将对象初始化为可用状态,只执行所需的操作,并且最好没有任何副作用。
一些小逻辑通常没问题(例如计算属性)。对于更复杂的逻辑,请考虑将私有构造函数与静态“工厂方法”结合使用。
您可以在此处阅读有关构造函数和最佳实践的更多信息。