मैं जेनिक्स का उपयोग कर identity map को लागू करने की कोशिश कर रहा हूं। मेरे पास एक अमूर्त वर्ग, संस्था, और संस्था के लिए मेरे मानचित्र पर एक व्युत्पन्न बाधा है। चूंकि मेरे मानचित्र को संस्थाओं को तुरंत चालू करने में सक्षम होना आवश्यक है, इसलिए मेरे मानचित्र में एक कन्स्ट्रक्टर बाधा भी है।सी # में जेनेरिक पहचान मानचित्र। सार्वजनिक कन्स्ट्रक्टर नहीं चाहते हैं
हालांकि, मानचित्र के लिए उपयोगी होने के लिए, इकाई सबक्लास को क्लाइंट कोड से तत्काल नहीं किया जाना चाहिए, जिसका अर्थ है कि मैं एक आंतरिक कन्स्ट्रक्टर और कोई सार्वजनिक निर्माता नहीं चाहता हूं। हालांकि, यह कन्स्ट्रक्टर बाधा के साथ संघर्ष करता है।
क्या मुझे कुछ याद आ रही है? वांछित परिणाम प्राप्त करने के लिए इसे पुन: सक्रिय करने का कोई तरीका है?
निम्न कोड को संकलित करता है के रूप में है, लेकिन, आदर्श, एंटिटी के उपवर्गों 'कंस्ट्रक्टर्स आंतरिक होगा:
public abstract class Entity
{
public int Id { get; protected internal set; }
}
public sealed class Widget : Entity
{
// Client code should not be allowed to instantiate entities.
// But the constraints on EntityMap require that entities have
// a public constructor.
public Widget() { }
}
public sealed class Gadget : Entity
{
public Gadget() { }
}
// The new() constraint is required so that Get() can instantiate Ts.
public class EntityMap<T> where T : Entity, new()
{
private Dictionary<int, T> _entities = new Dictionary<int, T>();
private object _getLock = new object();
public T Get(int id)
{
lock (_getLock)
{
if (!_entities.ContainsKey(id))
_entities.Add(id, new T() { Id = id });
}
return _entities[id];
}
// Client code should not be allowed to instantiate maps.
internal EntityMap() { }
}
// Ideally, the client would only be able to obtain Entity
// references through EntityMaps, which are only accessible
// through the ApplicationMap.
public static class ApplicationMap
{
public static EntityMap<Widget> Widgets = new EntityMap<Widget>();
public static EntityMap<Gadget> Gadgets = new EntityMap<Gadget>();
}
क्या बजाय TryGetValue उपयोग करने का लाभ है ContainsKey? क्या यह गति का मुद्दा है? – Lobstrosity