दिया की संदर्भ जाओ मैं कई शब्दकोशों है:एक संग्रह एक प्रकार
Dictionary<int, Type1> Type1Dictionary { get; set; }
Dictionary<int, Type2> Type2Dictionary { get; set; }
Dictionary<int, Type3> Type3Dictionary { get; set; }
Dictionary<int, Type4> Type4Dictionary { get; set; }
कहाँ Typei (i = 1..4)
एक ही आधार वर्ग (BaseType
) से हुआ है। मुझे एक ऐसी विधि चाहिए जो एक प्रकार के शब्दकोश के संदर्भ को वापस करे। बाद में, मैं कुछ कार्रवाई करने की तरह जोड़ें या कि शब्दकोश पर निकालें:
Type1 example = new Type1();
var dic = GetDictionary(example);
dic.Add(example.ID, example);
नोट्स: मैं अपने शब्दकोशों स्थापित करने के लिए के रूप में Dictionary<int, BaseType>
मैं कुछ इस तरह है, लेकिन लिख सकता है नहीं करना चाहती है कि नहीं होगा शब्दकोश के लिए एक संदर्भ वापसी:
Dictionary<int, BaseType> GetDictionary(BaseType myObject)
{
var dic = new Dictionary<int, BaseType>();
if(myObject is Type1)
{
//ideally I would return my Type1Dictionary here but I can't due type incompatibility
foreach(var x in Type1Dictionary)
{
dic.Add(x.Key, x.Value);
}
return dic;
}
if(myObject is Type2) { /*...*/ }
if(myObject is Type3) { /*...*/ }
if(myObject is Type4) { /*...*/ }
}
संपादित करें:
क्या मैं सच में चाहते हैं निम्नलिखित संरचना से बचने के लिए है:
AddObject(BaseType x)
{
Type1 x1 = x as Type1;
if(x1 != null) { Type1Dictionary.Add(x1.ID, x1); }
Type2 x2 = x as Type2;
if(x2 != null) { Type2Dictionary.Add(x2.ID, x2); }
Type3 x3 = x as Type3;
if(x3 != null) { Type3Dictionary.Add(x3.ID, x3); }
Type4 x4 = x as Type4;
if(x4 != null) { Type4Dictionary.Add(x4.ID, x4); }
}
RemoveObject(BaseType x)
{
Type1 x1 = x as Type1;
if(x1 != null) { Type1Dictionary.Remove(x1.ID); }
Type2 x2 = x as Type2;
if(x2 != null) { Type2Dictionary.Remove(x2.ID); }
Type3 x3 = x as Type3;
if(x3 != null) { Type3Dictionary.Remove(x3.ID); }
Type4 x4 = x as Type4;
if(x4 != null) { Type4Dictionary.Remove(x4.ID); }
}
लेकिन बजाय:
AddObject(BaseType x)
{
var dic = GetDictionary(x);
dic.Add(x.ID, x);
}
RemoveObject(BaseType x)
{
var dic = GetDictionary(x);
dic.Remove(x.ID);
}
आप एक शब्दकोष नहीं चाहते हैं जो 'int' से' बेसटाइप 'के नक्शे पर है, लेकिन आप एक शब्दकोश वापस करते हैं जो वही काम करता है? –
मैं 'टाइप 2' ऑब्जेक्ट्स को 'टाइप 1' के समान शब्दकोष में नहीं देना चाहता हूं। लेकिन किसी ऑब्जेक्ट को हटाने या जोड़ने के लिए मुझे वास्तव में परवाह नहीं है कि शब्दकोश का इलाज कैसे किया जाता है (यदि यह सही प्रकार का है)। मैंने जो कोड लिखा है वह मेरी समस्या को हल नहीं करता है, बीटीडब्ल्यू। – Sturm
विज़िटर पैटर्न के लिए उम्मीदवार की तरह लगता है, या 'गतिशील' का उपयोग करें और समस्या को डीएलआर में ले जाएं। –