在内存中是否有重写类实例的方法?

本文关键字:实例 方法 重写 内存 是否 | 更新日期: 2023-09-27 18:10:40

例如…我有一个类叫DisplayableUnit

代码中到处都有指向该类实例的变量,比如:

List<DisplayableUnit> known_units;
DisplayableUnit CopiedUnit;
DisplayableUnit EditingUnit;
DisplayableUnit CurrentUnit;

然后,例如,我需要用新创建的instanceB替换一些 instanca 。是否有可能重写 instanca 的类实例字节,因此所有先前指向 instanca 的其他变量将指向instanceB而不改变自己的指针?

我需要这个,因为我有很多指向实例的变量,所以很难全部改变。

我理想的方式是:known_units[5] = instanceB; //and after that all other vars will lead onto instanceB

在内存中是否有重写类实例的方法?

我提出两种可能的解决方案。

首先是以自动方式修改原始对象,例如使用http://valueinjecter.codeplex.com/,从而不必处理大量字段。

public void Change(DisplayableUnit other)
    {
        this.InjectFrom(other);
    }

第二种方法是让所有变量指向一个类型为DisplayableUnit的包装器,并通过Value属性访问内部对象。

public class Wrapper<T>
    {
        public T Value { get; set; }
    }