2013-02-07 35 views
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. 

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

基础类型和继承或接口类型如何?很难理解你想要实现的目标 - 你可以在插入 – Charleh

+2

之后对你正在做什么和你期望做的功能/列表发表评论吗? – MethodMan

+3

顺便说一句,你为什么使用结构而不是类呢?在这种情况下,更智能的_struct_将是_class_。 –

回答

4

它在我看来像你可以受益于在这种情况下的一些继承。由于部分是一般类型,并且您有更多特定类型,例如监视器和键盘,因此它是继承的最佳示例。因此,这将是这个样子:

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

+0

让我觉得难忘继承是要走的路,因为struct不支持这些,所以类是要走的路。 –

+0

是的。一个结构只能用于只包含几个字段的不可变类型,否则拷贝对象变得非常昂贵。另一种方法是让产品为不同的方面实现不同的接口,如“IPart”,“IWarranty”,“IServiceable”。 –