[英]C# Struct / Lookup Table
說我有一個聲明如下的結構:
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。 對所有結構和詞典集合使用通用接口
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];
}
}
您上面使用的語法不起作用,因為它的意思是“創建一個包含五個元素的AnotherStruct數組”。 但是,正如評論中提到的那樣,您確實應該考慮使用工廠模式。
但是,如果您確實要使用上面的模式,則可以對其稍加更改。 讓AnotherStruct數組保存每個結構的Type實例。 然后,您的“創建”行將更像:
structobject s = (structobject)Activator.CreateInstance(AnotherStruct[5]);
您可以在Assembly上使用反射(因為您將其包裝在DLL中)來獲取那些Type對象。
最后,除非您有充分的理由使用struct
(並了解所有細微差別,其中有許多細微差別),否則請堅持使用class
。
解決方案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;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.