如何在 C# 组合中正确处理变量

本文关键字:正确处理 变量 组合 | 更新日期: 2023-09-27 17:57:06

这里作曲的正确实现是什么?我有一类猫,它包含_gallonsOfMilkEaten变量,因为只有猫喝牛奶。然后我还有一个带有年龄的动物类,因为所有动物都有一定的年龄。现在,我需要在猫和狗类中使用年龄变量。

我应该这样做吗:

class Animal
{
    public float Age = 35;
}
class Cat
{
    private float _gallonsOfMilkEaten;
    private Animal _animal = new Animal();
    public void Meow()
    {
         Debug.log("This dog ate "+_gallonsOfMilkEaten+" gallons of milk and is " + _animal.Age+" years old." )}
    }
}

class Dog
{
    private float _bonesBurried;
    private Animal _animal = new Animal();
    public void Woof()
    {
       //...
    }
}

或者像这样,他们每个人都有自己的变量定义?

class Animal
{
}
class Cat
{
    private float _gallonsOfMilkEaten;
    private Animal _animal = new Animal();
    private float _age = 35;
    public void Meow()
    {
         Debug.log("This dog ate "+_gallonsOfMilkEaten+" gallons of milk and is " + _age+" years old." )}
    }
}

class Dog
{
    private float _bonesBurried;
    private Animal _animal = new Animal();
    private float _age = 35;
    public void Woof()
    {
       //...
    }
}

如何在 C# 组合中正确处理变量

首先,如果您有充分的理由使用组合而不是继承,则代码是有意义的。继承应该是默认选择,因为狗和猫ARE动物而不是HAVE动物。

你应该把年龄保持在Animal班上,如果你不这样做,那么上这门课有什么意义呢?但是,不应将其定义为公共字段,首选公共只读属性:

class Animal {
    private float _age = 35;
    public float Age {
       get {
         return this._age;
       }
    }
}    
class Cat {
    private float _gallonsOfMilkEaten;
    private Animal _animal = new Animal();
    public void Meow() {
         Debug.log("This dog ate "+_gallonsOfMilkEaten+" gallons of milk and is " + _animal.Age +" years old." )}
    }
} 
class Dog {
    private float _bonesBurried;
    private Animal _animal = new Animal();
    public void Woof() {
       //...
    }
}

我要发表一个相反的观点。 虽然您特别要求组合,但这个特定的用例并没有多大意义。 Cat s 和 Dog 没有动物,它们是动物,所以你真的应该在这里使用继承,而不是组合。

class Animal
{
    public float Age {get; protected set; }
}

那么你的Cat类和Dog类看起来像这样

class Cat : Animal
{
    private float _gallonsOfMilkEaten;
    public void Meow()
    {
        Debug.log("This dog ate " + _gallonsOfMilkEaten + " gallons of milk and is " + Age + " years old." )}
    }
}
class Dog : Animal
{
    private float _bonesBurried;
    public void Woof()
    {
       //...
    }
}

这允许CatDog使用Age成员,就好像它被合成到它们中一样(因为它是),但不会不必要地重复Animal作为成员的嵌套。 在您的特定用例中,这几乎可以肯定是您真正想要的。 在其他情况下,有时构图更好。 例如,在这里,Animal有一个Age,但Animal不是float