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_Thing
的调用?
如果我能让用户写 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()
并在当前程序集和引用它的所有程序集中执行此操作。
是否可以使用 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_Thing
的调用?
如果我能让用户写 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()
并在当前程序集和引用它的所有程序集中执行此操作。