Код: Выделить всё
#nullable enable
using System.Collections.Generic;
// Biology.dll
public abstract class Animal
{
public Animal() {}
}
public class Biome
{
private List animals = new();
public Biome() {}
public void AddAnimal(Animal a)
{
animals.Add(a);
}
public void Simulate() {}
}
// Program.exe
public class Dog : Animal {}
public class Centipede : Animal
{
private uint nLegs;
public Centipede(uint nLegs)
{
this.nLegs = nLegs;
}
}
public class Program
{
public static void Main()
{
Biome b = new();
b.AddAnimal(new Dog());
b.AddAnimal(new Centipede(100));
b.Simulate();
}
}
- Different subclasses of Animal can have different constructor parameters, so I can't use a generic function in Biome to construct new Animal objects (because generics can only use zero-parameter constructors)
- Объекты, по дизайну, не знают объекта Biome , который владеет им
Код: Выделить всё
Animal - Создание объектов Animal и регистрирует их с помощью Biome имеет чистый, интуитивно понятный синтаксис
Ниже моя лучшая попытка до сих пор:
Код: Выделить всё
#nullable enable
using System.Collections.Generic;
// Biology.dll
public abstract class Animal
{
protected internal Biome.IWeather weather;
public Animal() {} // CS8618 - Non-nullable field 'weather' must contain a non-null value when exiting constructor.
}
public class Biome
{
public interface IWeather {}
private class Weather : IWeather
{
internal Weather() {}
}
private Weather weather = new();
private List animals = new();
public Biome() {}
public void AddAnimal(Animal a)
{
a.weather = weather;
animals.Add(a);
}
public void Simulate() {}
}
// Program.exe
public class Dog : Animal {}
public class Centipede : Animal
{
private uint nLegs;
public Centipede(uint nLegs)
{
this.nLegs = nLegs;
}
}
public class Program
{
public static void Main()
{
Biome b = new();
b.AddAnimal(new Dog());
b.AddAnimal(new Centipede(100));
b.Simulate();
}
}
Подробнее здесь: https://stackoverflow.com/questions/797 ... -public-fa
Мобильная версия