如何使这个结构变得更聪明

时间:2013-02-07 15:42:01

标签: c# .net

我有这个结构,它是类的一部分。

  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

1 个答案:

答案 0 :(得分:4)

在我看来,在这种情况下你可以从一些继承中受益。由于part是一般类型,并且您有更多特定类型,例如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