![](/img/trans.png)
[英]How do I map a type from a CLR namespace in XAML from an assembly other than the one where it's declared?
[英]How do I find all the type dependecies of a given type in any CLR based language assembly?
我試圖找到給定類型所依賴的所有類型,包括接口,抽象類,枚舉,結構等。我想加載一個程序集,並打印出其中定義的所有類型的列表,以及他們的依賴。
到目前為止,我已經能夠找到CLR程序集依賴於使用Mono.Cecil的所有外部類型,例如
using System;
using Mono.Cecil;
using System.IO;
FileInfo f = new FileInfo("SomeAssembly.dll");
AssemblyDefinition assemDef = AssemblyFactory.GetAssembly (f.FullName);
List<TypeReference> trList = new List<TypeReference>();
foreach(TypeReference tr in assemblyDef.MainModule.TypeReferences){
trList.Add(tr.FullName);
}
此列表也可以使用mono disasembler獲得,例如“monodis SomeAssembly.dll --typeref”,但此列表似乎不包括基元,例如System.Void,System.Int32等
我需要單獨處理每種類型,並獲得給定類型所依賴的所有類型,即使類型在同一程序集中定義。 有沒有辦法使用Mono.Cecil或任何其他項目?
我知道可以通過加載程序集,然后迭代每個定義的類型,然后加載類型的IL並掃描它以獲取引用來完成,但我確信有更好的方法。 理想情況下,它也適用於匿名內部類。
如果在同一個程序集中定義了多個模塊,它也應該有效。
AJ,我有同樣的問題,我需要遍歷程序集中的類型,我決定使用Mono.Cecil。 我能夠遍歷每個類並且如果類中的屬性不是另一個類而不是CLR類型的方式是通過遞歸函數。
private void BuildTree(ModuleDefinition tempModuleDef , TypeDefinition tempTypeDef, TreeNode rootNode = null)
{
AssemblyTypeList.Add(tempTypeDef);
TreeNode tvTop = new TreeNode(tempTypeDef.Name);
// list all properties
foreach (PropertyDefinition tempPropertyDef in tempTypeDef.Properties)
{
//Check if the Property Type is actually a POCO in the same Assembly
if (tempModuleDef.Types.Any(q => q.FullName == tempPropertyDef.PropertyType.FullName))
{
TypeDefinition theType = tempModuleDef.Types.Where( q => q.FullName == tempPropertyDef.PropertyType.FullName)
.FirstOrDefault();
//Recursive Call
BuildTree(tempModuleDef, theType, tvTop);
}
TreeNode tvProperty = new TreeNode(tempPropertyDef.Name);
tvTop.Nodes.Add(tvProperty);
}
if (rootNode == null)
tvObjects.Nodes.Add(tvTop);
else
rootNode.Nodes.Add(tvTop);
}
這個函數由我的主要函數調用,其主旨是
public void Main()
{
AssemblyDefinition assemblyDef = AssemblyDefinition.ReadAssembly(dllname);
//Populate Tree
foreach (ModuleDefinition tempModuleDef in assemblyDef.Modules)
{
foreach (TypeDefinition tempTypeDef in tempModuleDef.Types)
{
BuildTree(tempModuleDef ,tempTypeDef, null);
}
}
}
看看NDepend - 它可以做到這一點,還有更多。
-Oisin
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.