【发布时间】:2015-03-17 11:49:09
【问题描述】:
我的问题是在示例代码中。 我如何限制开发人员传递真实参数。我尝试了一些关于泛型的方法,但我无法修复。
这里重要的是我想限制编译时间。所以我知道如何在运行时进行预防。
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.??
}
}
}
【问题讨论】:
-
这种设计是不可能的,只能在运行时抛出异常。
-
我认为你的意思是 compile time 而不是 design time。
-
@Oliver 是的编译时间。谢谢指正。
标签: c# design-patterns methods parameter-passing restrict