Вот мои реализации:
- Inherited Dictionary
Код: Выделить всё
public class GenericDictionary: Dictionary { public T GetValue(string key) { if(TryGetValue(key,out var value) && value is T val) return val; if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List)) { var emptyList = Activator.CreateInstance(typeof(T)); return (T)emptyList!; } throw new InvalidOperationException($"Type mismatch on key {key}"); } } - Методы расширения
3. Создан
Код: Выделить всё
public static class GenericDictionaryExtensions { public static T GetList(this Dictionary dict, string key) { if (dict.TryGetValue(key, out var value)) { if (value is T typedValue) return typedValue; if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List) && value is IEnumerable enumerable) { var list = Activator.CreateInstance(typeof(T), enumerable)!; return (T)list; } } if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List)) { return (T)Activator.CreateInstance(typeof(T))!; } throw new InvalidOperationException($"Type mismatch on key '{key}'"); } }Изменить: опечаткаКод: Выделить всё
public class GenericDictionary { private Dictionary _dict = new(); public T GetValue(string key) { if (_dict.TryGetValue(key, out var value) && value is T typedValue) return typedValue; if (typeof(T).IsGenericType && typeof(T).GetGenericTypeDefinition() == typeof(List)) { var emptyList = Activator.CreateInstance(typeof(T)); return (T)emptyList!; } throw new InvalidOperationException($"type doesnt match"); } }
Подробнее здесь: https://stackoverflow.com/questions/798 ... -when-work