2011-05-08 43 views
1

說我有一個結構中聲明如下所示:C#結構/查找表

public struct Test 
{ 
    public static int Width = 5; 
    ... 
    public static int[] Value = new int[1]{ 0 }; 
} 

現在我想要做的就是從其他結構內調用此方法,但我必須知道如何。我試圖做會(在我心中)如下所示:

public struct AnotherStruct 
{ 
    public (type of struct) this[int key] 
    { 
     get 
     { 
      switch(key) 
      { 
       case 1: 
        return (another struct); 
       default: 
        return null; 
      } 
     } 
    } 
} 

我的最終目標是,我想使用的代碼看起來像以下,而無需創建對象的實例:

structobject s = new AnotherStruct[5]; 

所以這個「查找表」將在另一個項目中創建和構建,則稱爲從我的主要項目的DLL。由於我在其他地方構建dll並調用它,我希望能夠將dll加載到內存中一次,然後我只能從我的主項目中引用該內存。然後,我將分配一部分內存,我的代碼將引用它,避免需要創建此查找表的單個實例(從而避免分配內存和存儲新實例所需的時間開銷)。從長遠來看,我節省的時間將是非常有益的,所以我希望我能以某種方式讓這個工作。

我希望這不是太混亂,但讓我知道是否需要澄清。

編輯 這是在一個網站上使用,所以我真的需要一個對象持久存在於所有連接中,並在代碼初次加載時創建一次。同樣的想法,但也許這會使更簡單的解決方案?

+1

看起來你需要一個工廠模式。 – 2011-05-08 00:11:11

+0

@Etienne de Martel您可以創建一個簡單的例子,說明如何從dll的角度和從主項目中工作。沒有真正的幻想。我以前從未使用過工廠模式,而我的有限研究表明它顯示它相當參與。 – JesseBuesking 2011-05-08 00:28:18

+0

一個細微差別:結構是值類型,所以爲了能夠返回null,需要使用特殊的可空結構類型'Nullable '或'Test?'。 – BoltClock 2011-05-08 00:54:12

回答

0

解決方案#2。放棄整個ID理念,只使用結構類型和泛型。

public struct St1 
{ 
} 
public struct St2 
{ 
} 

public class Factory<T> 
    where T : struct 
{ 
    static T _new = new T(); //cached copy of structure 

    public static T New { get { return _new; } }   
} 


class Program 
{ 
    static void Main(string[] args) 
    { 
     St1 x1 = Factory<St1>.New; 
     St1 x2 = Factory<St1>.New; 
     St1 x3 = Factory<St1>.New; 
     St2 y1 = Factory<St2>.New; 
     St2 y2 = Factory<St2>.New; 
    } 
} 
0

解決方案#1。使用所有結構的通用接口和一本字典收集

public interface IStr { } 

public struct St1 : IStr 
{ 
    public static int ID = 1; 
} 
public struct St2 : IStr 
{ 
    public static int ID = 2; 
} 

public class StructFactory : System.Collections.ObjectModel.KeyedCollection<int, IStr> 
{ 
    public static StructFactory Default = new StructFactory(); 
    protected override int GetKeyForItem(IStr item) 
    { 
     FieldInfo finfo = item.GetType().GetField("ID", 
      BindingFlags.Static | BindingFlags.Public); 

     return (int)finfo.GetValue(item); 
    } 

    public StructFactory() 
    { 
     Add(new St1()); 
     Add(new St2()); 
    } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     St1 x = (St1)StructFactory.Default[1]; 
     St2 y = (St2)StructFactory.Default[2]; 
    } 
} 
0

您使用上面將無法工作,因爲這意味着語法「創建AnotherStruct數組與它五行」。然而正如評論中提到的那樣,你真的應該考慮使用工廠模式。

但是,如果你真的想使用上面的模式,你可以稍微改變它。讓你的AnotherStruct數組保存每個結構體的Type實例。然後,你的「創作」行會看起來更像:

structobject s = (structobject)Activator.CreateInstance(AnotherStruct[5]); 

您可以在大會使用反射(因爲你是在DLL中包裝它)來獲取這些類型的對象。

最後,除非你有一個很好的理由使用struct(並瞭解所有細微差別,其中有幾個),堅持class