2010-11-15 148 views

回答

20

就「盒子裏的東西」而言,只能使用ModuleDefinition.Import API。

要從TypeReference變爲System.Type,您需要使用Reflection和AssemblyQualifiedName手動查找它。請注意,塞西爾使用IL約定來逃避嵌套類等,所以你需要應用一些手動更正。

如果你只想解決非泛型,非嵌套類型,你應該沒問題。

要從TypeReferenceTypeDefition(如果那是你的意思),你需要到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源代碼。

+0

還要注意的是Mono.Cecil能未建通過System.Reflection(作爲一個獨立的庫),這意味着沒有直接的方法將它們轉換爲對方。你應該仍然能夠做到這一點,但它不會看起來不錯。 – ShdNx 2010-11-15 13:07:07

+0

那麼如何用反射來查找類型?你有一個反射嵌套類型和cecil嵌套類型的例子嗎? – Will 2010-11-15 15:57:02

+7

而不是手動添加「,」,您可以使用Assembly.CreateQualifiedName(tr.Module.Assembly.FullName,tr.FullName)。 – user276648 2012-05-29 08:59:30

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回答這個