有没有办法从Mono.Cecil中的TypeReference转到Type?Mono.Cecil类型引用类型?
18
A
回答
20
就“盒子里的东西”而言,只能使用ModuleDefinition.Import
API。
要从TypeReference
变为System.Type
,您需要使用Reflection和AssemblyQualifiedName
手动查找它。请注意,塞西尔使用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源代码。
2
泛型类型,你需要这样的事:
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回答这个
还要注意的是Mono.Cecil能未建通过System.Reflection(作为一个独立的库),这意味着没有直接的方法将它们转换为对方。你应该仍然能够做到这一点,但它不会看起来不错。 – ShdNx 2010-11-15 13:07:07
那么如何用反射来查找类型?你有一个反射嵌套类型和cecil嵌套类型的例子吗? – Will 2010-11-15 15:57:02
而不是手动添加“,”,您可以使用Assembly.CreateQualifiedName(tr.Module.Assembly.FullName,tr.FullName)。 – user276648 2012-05-29 08:59:30