我有一个这样的课:
public class Meta
{
public string Height { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我想在课堂上添加一些内容,但我不知道该怎么做.我想要的是高度只能设置为"高"或"短".未来可能会有更多的事情,但现在只有这两者之间的选择.另外我希望它在构造函数中默认为"Short".我想我需要使用枚举,但我不知道该怎么做.
有人可以解释一下 我非常感谢.
是的,您可以使用枚举:
public enum Height
{
Short = 0,
Tall = 1;
}
public class Meta
{
public Height Height { get; private set; }
public Meta(Height height)
{
if (!Enum.IsDefined(typeof(Height), height))
{
throw new ArgumentOutOfRangeException("No such height");
}
this.Height = height;
}
}
Run Code Online (Sandbox Code Playgroud)
(如果希望属性可写,则需要将验证放在setter中.)
您需要验证,因为枚举实际上只是不同类型的整数值.例如,如果没有验证,这将很好地进行:
new Meta((Height) 1000);
Run Code Online (Sandbox Code Playgroud)
但对任何来电者来说显然毫无意义.
| 归档时间: |
|
| 查看次数: |
89 次 |
| 最近记录: |