Mono.Cecil可以用属性替换字段吗?

时间:2017-01-31 04:18:02

标签: c# unity3d mono mono.cecil

是否可以使用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;
    }
}

如果有可能,可以有效地完成吗? I.E.然后,我是否需要遍历每个引用程序集中每种类型的每个方法,以通过调用属性Thing来替换get_Thing的每个实例?

如果我可以让用户写public static Something Thing { get; } = new Something(...);所以它已经是一个属性会更容易,但我不能,因为Unity的编译器不支持属性初始化。

注意:我对使用IL几乎一无所知。

1 个答案:

答案 0 :(得分:1)

是的,使用Cecil,您可以轻松删除字段并添加具有相同名称的属性,但这会更改您的API表面,并且您必须查找所有

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

通过

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

并在当前程序集和引用它的所有程序集中执行此操作。