Last active
April 24, 2019 07:00
-
-
Save hiiru/f106fd974564b8d74f9ed3253d3ec632 to your computer and use it in GitHub Desktop.
Reflection type lookup and constructor lookup with cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static readonly ConcurrentDictionary<string, Type> _typeCache = new ConcurrentDictionary<string, Type>(); | |
public static Type GetTypeByFullName(string fullName) | |
{ | |
if (_typeCache.TryGetValue(fullName, out Type type)) | |
return type; | |
var paramTypes = GetAllTypesOf(typeof(Param)); | |
if (paramTypes.Any()) | |
{ | |
var match = paramTypes.FirstOrDefault(x => x.FullName == fullName); | |
if (match != null) | |
{ | |
type = match; | |
} | |
} | |
_typeCache[fullName] = type; | |
return type; | |
} | |
private static IEnumerable<Type> GetAllTypesOf(Type baseType) | |
{ | |
var platform = Environment.OSVersion.Platform.ToString(); | |
var runtimeAssemblyNames = DependencyContext.Default.GetRuntimeAssemblyNames(platform); | |
return runtimeAssemblyNames | |
.Select(Assembly.Load) | |
.SelectMany(a => a.ExportedTypes) | |
.Where(t => baseType.IsAssignableFrom(t)); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static readonly ConcurrentDictionary<Type, Func<object>> _ctxLookup = new ConcurrentDictionary<Type, Func<object>>(); | |
public static object CreateObject(Type type) | |
{ | |
var ctx = _ctxLookup.GetOrAdd(type, x => Expression.Lambda<Func<object>>(Expression.New(type)).Compile()); | |
if (ctx == null) | |
return null; | |
return ctx(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace ExampleModels { | |
public abstract class Param | |
{ | |
} | |
public class TextParam : Param | |
{ | |
public string Text { get; set; } | |
} | |
public class IntParam : Param | |
{ | |
public int Number { get; set; } | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fullName="ExampleModels.IntParam"; | |
var type=GetTypeByFullName(fullName); | |
var instance=CreateObject(type); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment