0

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

  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.

ETC..

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.

ETC..

insert(monitor);
insert(keyboard);

我能以更聪明的方式做到这一点吗?我正在使用.net 3.5

4

1 回答 1

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"; }}
    ...
}

您会在 Inheritance 上找到很多资源,我强烈建议您查看它们,因为它们将显着提高您的生产力和效率。这是一个例子: http: //msdn.microsoft.com/en-us/library/ms173149 (v=vs.80).aspx

于 2013-02-07T15:52:31.943 回答