有什么方法可以从Mono.Cecil中的TypeReference转换为类型吗?
发布于 2010-11-15 20:47:29
就“盒子里有什么”而言,只能反过来使用ModuleDefinition.Import应用编程接口。
要将TypeReference转换为System.Type,您需要使用反射和AssemblyQualifiedName手动查找它。请注意,Cecil使用IL约定来转义嵌套类等,因此您需要应用一些手动更正。
但是,如果您只想解析非泛型、非嵌套类型,则应该没问题。
要从TypeReference转到TypeDefition (如果这是您的意思),您需要使用TypeReference.Resolve();
请求的代码示例:
TypeReference tr = ...
Type.GetType(tr.FullName + ", " + tr.Module.Assembly.FullName);
// will look up in all assemnblies loaded into the current appDomain and fire the AppDomain.Resolve event if no Type could be found反射中使用的约定在here中进行了解释,对于Cecil约定,请参阅Cecil源代码。
发布于 2014-07-29 20:52:51
对于泛型类型,您需要类似以下内容:
public static Type GetMonoType(this TypeReference type)
{
return Type.GetType(type.GetReflectionName(), true);
}
private static string GetReflectionName(this TypeReference type)
{
if (type.IsGenericInstance)
{
var genericInstance = (GenericInstanceType)type;
return string.Format("{0}.{1}[{2}]", genericInstance.Namespace, type.Name, String.Join(",", genericInstance.GenericArguments.Select(p => p.GetReflectionName()).ToArray()));
}
return type.FullName;
}请注意,此代码不处理嵌套类型,请检查@çJohannesRudolph
https://stackoverflow.com/questions/4184384
复制相似问题