Den*_*oğa 0 c# methods design-patterns parameter-passing restrict
我的问题是示例代码.如何限制开发人员传递真实参数.我尝试了一些关于泛型但我无法解决的问题.
这里重要的是我想限制编译时间.所以我知道如何在运行时防止.
namespace TheLiving
{
public interface IFood
{
int Protein { get; set; }
int Carbohydrate { get; set; }
}
public interface IMeat : IFood
{
int Nitrogen { get; set; }
}
public interface IVegetable : IFood
{
int Vitamin { get; set; }
}
public class Veal : IMeat
{
public int Protein { get; set; }
public int Carbohydrate { get; set; }
public int Nitrogen { get; set; }
}
public class Spinach : IVegetable
{
public int Protein { get; set; }
public int Carbohydrate { get; set; }
public int Vitamin { get; set; }
}
public interface IEating
{
void Eat(IFood food);
}
public class Lion : IEating
{
public int Protein { get; set; }
public int Carbohydrate { get; set; }
public int Nitrogen { get; set; }
//But lion is eating only Meat. So any developer can pass vegatable to lion for eating.
//May be god is not a good developer. So i want restrict him on Compile Time!! for passing only Meat. :)
//The important thing here is i want restrict on Compile Time not RunTime!!!
public void Eat(IFood food)
{
Protein = food.Protein;
Carbohydrate = food.Carbohydrate;
//Nitrogen = ?? //So i know that i can cast and validate food but i want ensure this on DesignTime!!
}
}
public class Sheep : IEating
{
public int Protein { get; set; }
public int Carbohydrate { get; set; }
public int Vitamin { get; set; }
public void Eat(IFood food)
{
Protein = food.Protein;
Carbohydrate = food.Carbohydrate;
//Vitamin = food.??
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为你必须有接口IHerbivore,ICarnivore以及IOmnivore允许这种在设计时.
public interface IHerbivore
{
void Eat(IVegetable food);
}
public interface ICarnivore
{
void Eat(IMeat food);
}
public interface IOmnivore : IHerbivore, ICarnivore
{
}
Run Code Online (Sandbox Code Playgroud)
然后你的狮子可以成为一个ICarnivore只能吃肉的人