2013-02-07 55 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」。 –