Skip to content

Instantly share code, notes, and snippets.

@einarwh
Created April 28, 2012 19:07
Show Gist options
  • Select an option

  • Save einarwh/2521365 to your computer and use it in GitHub Desktop.

Select an option

Save einarwh/2521365 to your computer and use it in GitHub Desktop.
Helper class to facilitate looking up TypeReference objects for types.
public class TypeResolver
{
private readonly TypeDefinition _typeDef;
private readonly IDictionary<Type, TypeReference> _typeRefs =
new Dictionary<Type, TypeReference>();
private readonly TypeSystem _ts;
private readonly ModuleDefinition _systemModule;
private readonly ModuleDefinition _mscorlibModule;
public TypeResolver(TypeDefinition typeDef)
{
_typeDef = typeDef;
_ts = typeDef.Module.TypeSystem;
Func<string, ModuleDefinition> getModule =
m => typeDef.Module.AssemblyResolver.Resolve(m).MainModule;
_systemModule = getModule("system");
_mscorlibModule = getModule("mscorlib");
}
public TypeReference Object
{
get { return _ts.Object; }
}
public TypeReference String
{
get { return _ts.String; }
}
public TypeReference Void
{
get { return _ts.Void; }
}
public TypeReference INotifyPropertyChanged
{
get { return LookupSystem(typeof(INotifyPropertyChanged)); }
}
public TypeReference PropertyChangedEventHandler
{
get { return LookupSystem(typeof(PropertyChangedEventHandler)); }
}
public TypeReference PropertyChangedEventArgs
{
get { return LookupSystem(typeof(PropertyChangedEventArgs)); }
}
public TypeReference Delegate
{
get { return LookupCore(typeof(Delegate)); }
}
public TypeReference Interlocked
{
get { return LookupCore(typeof(Interlocked)); }
}
private TypeReference LookupCore(Type t)
{
return Lookup(t, _mscorlibModule);
}
private TypeReference LookupSystem(Type t)
{
return Lookup(t, _systemModule);
}
private TypeReference Lookup(Type t, ModuleDefinition moduleDef)
{
if (!_typeRefs.ContainsKey(t))
{
var typeRef = moduleDef.Types.FirstOrDefault(
td => td.FullName == t.FullName);
if (typeRef == null)
{
return null;
}
var importedTypeRef = _typeDef.Module.Import(typeRef);
_typeRefs[t] = importedTypeRef;
}
return _typeRefs[t];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment