/// <summary> /// Create instance of Type with parameters, or returns Instance property if it exists /// </summary> /// <param name="type">Returned type</param> /// <param name="args">Constructor arguments</param> /// <returns></returns> public static object CreateInstance(this Type type, params object[] args) { type.NullTest(nameof(type)); string key = (args.Length == 0) ? type.FullName : $"{type.FullName}_{ string.Join("_", args.Select(o => o.GetType().Name))}"; object instance = null; if (_ctorCache.TryGetValue(key, out var ctor)) { return(ctor(args)); } else if (_instancesList.TryGetValue(type, out instance)) { return(instance); } instance = type.GetField("Instance", BindingFlags.Public | BindingFlags.Static)?.GetValue(null); if (instance != null) { _instancesList.AddOrUpdate(type, instance); return(instance); } ctor = GetCtor(type.GetConstructor(args.Select(o => o.GetType()).ToArray())); _ctorCache[key] = ctor; return(ctor(args)); }
public static T GetValue <T>(this MapTable <string, object> d, string key, T defaultValue = default) { if (d != null && d.TryGetValue(key, out object result)) { return(result.CastAs <T>()); } return(defaultValue); }
public static Type GetTypeByAssemblyQualifiedName(string name) { if (!_typeCache.TryGetValue(name, out Type t)) { t = Type.GetType(name); _typeCache.Add(name, t); } return(t); }
public static IEnumerable <Type> GetTypes(Type type) { if (_iList.TryGetValue(type, out var l)) { return(l); } l = GetImplements(type).ToList(); _iList.TryAdd(type, l); return(l); }
/// <summary> /// For perfomance test /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <param name="args"></param> /// <returns></returns> public static T CreateInstance2 <T>(this Type type, params object[] args) { string key = (args.Length == 0) ? type.FullName : $"{type.FullName}_{ string.Join("_", args.Select(o => o.GetType().Name))}"; if (_ctorCache2.TryGetValue(key, out var ctor)) { return((T)ctor.Invoke(args)); } ctor = type.GetConstructor(args.Select(o => o.GetType()).ToArray()); lock (_obj4Lock) _ctorCache2[key] = ctor; return((T)ctor.Invoke(args)); }