如何使这个结构更智能
本文关键字:智能 结构 何使这 | 更新日期: 2023-09-27 17:58:16
我有一个结构,它是类的一部分。
public struct PartStruct
{
public string name;
public string filename;
public string layer2D;
public string layer3D;
public TypeOfPart type;
public int hight;
public int depth;
public int length;
public int flooroffset;
public int width;
public int cellingoffset;
}
这个结构的每个实例都代表一个具有不同属性的部分,我只使用一种结构类型,因为我有这个函数:
public void insert(Partstruct part){//large code to insert the part}
示例:
Partstruct monitor = new Partstruct();
monitor.name = "mon1";
monitor.file = "default monitor file name.jpg";//this is a const for each new monitor
monitor.TypeofPart = monitor;
monitor.layer2d = "default monitor layer";//this will be the same for each new monitor.
等等。。
Partstruct keyboard= new Partstruct();
keyboard.name = "keyboard1";
keyboard.file = "default keyboard file name.jpg";//this is a const for each new keyboard
keyboard.TypeofPart = keyboard;
keyboard.layer2d = "default keyboard 2d layer";//this will be the same for each new keyboard.
keyboard.layer3d = "default keyboard 3d layer"//this will be the same for each new keyboard.
等等。。
insert(monitor);
insert(keyboard);
我能用更聪明的方法吗?我使用的是.net 3.5
在我看来,在这种情况下,您可以从一些继承中受益。由于零件是一种通用类型,并且您有更具体的类型,如Monitor和Keyboard,因此它是继承的完美示例。所以它看起来像这样:
public class Part
{
public virtual string Name { get { return "not specified"; } }
public virtual string FileName { get { return "not specified"; } }
public virtual string Layer2D { get { return "not specified"; } }
public virtual string Layer3D { get { return "not specified"; } }
...
}
public class Monitor : Part
{
public override FileName { get { return "default monitor"; } }
public override Layer2D { get { return "default monitor layer"; }}
...
}
和
public class Keyboard : Part
{
public override FileName { get { return "default keyboard filename.jpg"; } }
public override Layer2D { get { return "default keyboard 2d layer"; }}
...
}
你会在继承上找到很多资源,我强烈建议你看看它们,因为它们会显著提高你的生产力和效率。以下是一个示例:http://msdn.microsoft.com/en-us/library/ms173149(v=vs.80).aspx