[英]Properly using a custom variable type (struct) in class
我正在尝试通过正在尝试实施的新课程来思考,并不确定自己是好是坏。 我想创建一个包含设备设置(例如英寸与公制)以及对应于设置的代码的类。 我认为最好有这样的代码:
Device myDevice = new Device();
myDevice.units = Device.Inches;
myDevice.MoveTo(1,2,3, Device.Rapid);
设备类文件将是:
class Device
{
public static DeviceUnit Inches = DeviceUnit("G21");
public static DeviceUnit Metric = DeviceUnit("G20");
public static DeviceMovement Rapid = DeviceMovement("G00");
public static DeviceMovement Feed = DeviceMovement("G01");
public DeviceUnit units;
public Device()
{
// Default to metric system
units = Device.Metric;
}
public Device(DeviceUnit customUnit)
{
units = customUnit;
}
public MoveTo(float x, float y, float z, DeviceMovement movement)
{
string command = string.Format($"{units.gcode} {movement.gcode} ");
command += string.Format($"X{x} Y{y} Z{z}\r\n");
Debug.Write(command);
}
}
设备单元结构:
public struct DeviceUnit
{
public string gcode;
public DeviceUnit(string code)
{
gcode = code;
}
}
DeviceMovement结构:
public struct DeviceMovement
{
public string gcode;
public DeviceUnit(string code)
{
gcode = code;
}
}
我担心的是,我最终可能会在使用的结构数量上被“过度杀伤”。 我已经在考虑应该另外存储增量(G90)与绝对(G91)定位。 我想使其具有灵活性,以便将来可以从XML配置文件中加载gcode
字符串,以便为新的计算机配置快速创建新的XML文件。
使用多个结构对于此任务而言是否过于矫kill过正?
我应该以某种方式将结构结合在一起吗?
如果结构具有表示复杂对象的多个属性,则该结构具有含义。
我发现您的结构DeviceUnit,DeviceMovement只是字符串类型的一个属性,那么为什么是struct?
让DeviceUnit,DeviceMovement字符串属性。 可是等等 :)
Q: Is using multiple structs too overkill for this task?
答:不可以,如果Struct用于描述具有许多属性的对象(可能是复杂的设备属性),则它并不是多余的。
例:
public struct Dimension
{
//avoid using constructor. You can initialize with object initializer
public int x;
public int y;
public int z;
}
例如:Windows的所有设备都存储在WMI类中,例如Win32_Printer WMI,它具有40多个属性,并且大多数属性是一个复杂的对象。
q: Should I combine the structs together somehow?
答:您只需定义一个名为Device的类,它具有属性和方法。 如果属性之一是复杂对象,则其类型应为struct或class。 您为设备构建对象模型 ,因此请仔细选择属性的类型。 但是在您的代码中,实际上您根本不需要该结构,请使用简单的属性,例如:
public static string Inches {get;set;} = "G21"; // in c#6 you can initialize properties
我的问题:为什么选择静态属性?
我的问题:为什么用默认值初始化属性。
答:您可以为每个设备创建xml文件并在对象实例化期间加载它,这为您提供了更多功能:
使用一个或多个专业类表示您的设备您可以将以下方法添加到您的设备类中:
public LoadDevice(string xmlFilename)
{
// read xml file , e.g Linq to xml
// set properties
}
Here your ceiling is the sky :)
顺便说一句,如果结构具有构造函数,则应使用new关键字。 因此应该:
public static DeviceUnit Inches = new DeviceUnit("G21"); //:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.