2014-02-13 80 views
1

我想獲取現有屬性設置器的屬性定義。但是,即使我知道它存在,SetMethod總是顯示爲空。如何獲取屬性設置指令?

這是迄今爲止我嘗試:

public class Bar 
{ 
    private Foo _foo; 
    public virtual Foo Foo { get { return _foo; } { set { _foo = value; } } 
} 

var moduleDefinition = ModuleDefinition.ReadModule(assemblyFile); 

var propertyTypeReference = new TypeReference(
    typeof(Foo).Namespace, 
    typeof(Foo).Name, 
    moduleDefinition, 
    null 
); 

var propertyDefinition = new PropertyDefinition(
    "Foo", 
    Mono.Cecil.PropertyAttributes.None, 
    propertyTypeReference 
); 

//always throws NullReferenceException because SetMethod is always null. 
var instructions = propertyDefinition.SetMethod.Body.Instructions.ToList(); 

(我在微軟.NET CLR運行)。

如何使用Mono.Cecil獲取現有屬性的setter指令?

回答

1

您應該從ModuleDefinition.Types得到TypeDefinitionFoo,進而獲得PropertyDefinition用於FooTypeDefinition.Properties。稍後您可以獲取設置方法及其說明。

請勿使用任何構造函數,因爲它們用於構建新的元數據,不會分析現有的元數據。在您的代碼中調用它們實際上會構建新的引用/定義,並且預期會發生異常,因爲您沒有正確構建它們。

0

您可以嘗試asm.MainModule.GetType(「ClassFullname」)。Methods.First(m => m.Name ==「set_Foo」)