【问题标题】:Can Mono.Cecil replace a field with a property?Mono.Cecil 可以用属性替换字段吗?
【发布时间】:2017-01-31 04:18:01
【问题描述】:

是否可以使用 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。然后我是否需要遍历每个引用程序集中每种类型中的每个方法,以调用属性的 get_Thing 来替换 Thing 的每个实例?

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

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

【问题讨论】:

    标签: c# unity3d mono mono.cecil


    【解决方案1】:

    是的,使用 Cecil 您可以轻松地删除一个字段并添加一个同名的属性,但这会改变您的 API 表面,您必须查找所有的

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

    通过

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

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

    【讨论】:

      猜你喜欢
      • 2012-02-13
      • 1970-01-01
      • 2020-12-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多