[英]How can I make it so my class variables can only be set to one of three choices?
I have a class like this:我有一个像这样的 class :
public class Meta
{
public string Height { get; set; }
}
I would like to add some things to the class but I'm not sure how to do it.我想在 class 中添加一些东西,但我不知道该怎么做。 What I would like is for the Height to only be able to be set to either "Tall" or "Short".我想要的是高度只能设置为“高”或“短”。 Maybe more things in the future but for now it would be a choice just between those two.也许将来会有更多的事情,但现在只能在这两者之间做出选择。 Also I would like it to default to "Short" in the constructor.我也希望它在构造函数中默认为“Short”。 I think I would need to use an Enums but I am not sure how to do this.我想我需要使用枚举,但我不知道该怎么做。
Could someone explain.有人可以解释一下。 I would very much appreciate.我将非常感激。
Yes, you could use an enum:是的,您可以使用枚举:
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;
}
}
(If you want the property to be writable, you need to put the validation in the setter.) (如果您希望属性可写,则需要将验证放入 setter。)
You need the validation because enums are really just differently-typed integer values.您需要验证,因为枚举实际上只是不同类型的 integer 值。 For example, without the validation this would proceed fine:例如,如果没有验证,这将正常进行:
new Meta((Height) 1000);
but it would obviously be meaningless to any callers.但这对任何来电者来说显然毫无意义。
You could define an enum with the possible values:您可以使用可能的值定义一个枚举:
public enum HeightTypes
{
Tall,
Short
}
and then use this as the type of the Height
property:然后将其用作Height
属性的类型:
public class Meta
{
public Meta()
{
// Set the Height property to Short by default in the constructor
Height = HeightTypes.Short;
}
public HeightTypes Height { get; set; }
}
Now when you have an instance of the Meta class you could set its Height property only to Tall or Short:现在,当您拥有 Meta class 的实例时,您可以仅将其 Height 属性设置为 Tall 或 Short:
var meta = new Meta();
meta.Height = HeightTypes.Tall;
Define an Enum.定义一个枚举。
public Enum Heights
{
Tall,
Short
}
and then define your property to be of type enum然后将您的属性定义为枚举类型
public Heights Height { get; set; }
see http://msdn.microsoft.com/en-us/library/system.enum.aspx for more info有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/system.enum.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.