簡體   English   中英

Mono.Cecil 可以用屬性替換字段嗎?

[英]Can Mono.Cecil replace a field with a property?

是否可以使用 Cecil 用屬性替換字段? 具體來說:

// Replace this.
public static readonly Something Thing = new Something(...);

// With this.
private static readonly Something _Thing = new Something(...);

public static Something Thing
{
    get
    {
        // My goal is to insert some extra code here, which I can't do if it's a field.
        return _Thing;
    }
}

如果可能的話,能否有效地完成? IE 那么我是否需要遍歷每個引用程序集中每種類型的每個方法,以將Thing每個實例替換為對屬性的get_Thingget_Thing

如果我可以讓用戶編寫public static Something Thing { get; } = new Something(...); public static Something Thing { get; } = new Something(...); 所以它已經是一個屬性,但我不能,因為 Unity 的編譯器不支持屬性初始值設定項。

注意:我對與 IL 合作幾乎一無所知。

是的,使用 Cecil,您可以輕松刪除字段並添加具有相同名稱的屬性,但這會改變您的 API 表面,您必須查找所有

IL_XXXX:  ldsfld class [MyAssembly]Something [MyAssembly]MyClass::Thing

經過

IL_XXXX:  call class [MyAssembly]Something class [MyAssembly]MyClass::get_Thing()

並在當前程序集和所有引用它的程序集中執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM