每个实例销毁对象

时间:2014-07-31 21:46:27

标签: c# constructor garbage-collection destroy

对于一个简单的问题我有几个更复杂的答案,所以我会问我的情况问题,因为我不能完全弄清楚该做什么除了那些其他答案。垃圾收集似乎是一个危险区域,所以我会谨慎行事。

我有一个Measurement对象,其中包含Volume个对象和一个Weight对象。根据使用的构造函数,我想销毁相反的对象,也就是说,如果用户添加了体积测量,我想根除该实例的权重元素,因为它在那时只是膨胀。该怎么办?

编辑澄清:

public class RawIngredient
{
    public string name { get; set; }
    public Measurement measurement;

    public RawIngredient(string n, double d, Measurement.VolumeUnits unit)
    {
        name = n;
        measurement.volume.amount = (decimal)d;
        measurement.volume.unit = unit;

        //I want to get rid of the weight object on this instance of measurement
    }

    public RawIngredient(string n, double d, Measurement.WeightUnits unit)
    {
        name = n;
        measurement.weight.amount = (decimal)d;
        measurement.weight.unit = unit;

        //I want to get rid of the volume object on this instance of measurement
    }
}

再次编辑以显示Measurement

public class Measurement
{

    public enum VolumeUnits { tsp, Tbsp, oz, cup, qt, gal }
    public enum WeightUnits { oz, lb }

    public Volume volume;
    public Weight weight;
}

VolumeWeight是包含两个字段的简单类。

3 个答案:

答案 0 :(得分:2)

首先,需要销毁什么?这发生在ctor中,所以不要创建你不想要的那个。

class Measurement 
{
    public Volume Volume {get; set;}
    public Weight Weight {get; set;}

   public Measurement (Volume v) { Volumme = v; Weight = null;}
   public Measurement (Weight w) { Volumme = null; Weight = w;}

}

答案 1 :(得分:1)

如果您在Measurement构造函数中,那么就不要创建非必需类型;它将保留为null的默认值(只要VolumeWeight是引用类型而不是结构),任何尝试引用错误类型都会引发异常。

只要Measurement对象在范围内,垃圾收集器就无法收集非必需类型,因为它将在Measurement实例的范围内,理论上可能是无论你在现实中的实际意图如何,都可以随时创建。

答案 2 :(得分:1)

如果对象实现了IDisposable,您应该调用它们的Dispose方法并确保它们不再被引用或处理。

Dispose之后(如有必要),您可以将未使用的对象设置为null

  1. 参考:http://blog.stephencleary.com/2010/02/q-should-i-set-variables-to-null-to.html