簡體   English   中英

我怎樣才能使我的 class 變量只能設置為三個選項之一?

[英]How can I make it so my class variables can only be set to one of three choices?

我有一個像這樣的 class :

public class Meta
{
    public string Height { get; set; }
}

我想在 class 中添加一些東西,但我不知道該怎么做。 我想要的是高度只能設置為“高”或“短”。 也許將來會有更多的事情,但現在只能在這兩者之間做出選擇。 我也希望它在構造函數中默認為“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;
    }
}

(如果您希望屬性可寫,則需要將驗證放入 setter。)

您需要驗證,因為枚舉實際上只是不同類型的 integer 值。 例如,如果沒有驗證,這將正常進行:

new Meta((Height) 1000);

但這對任何來電者來說顯然毫無意義。

您可以使用可能的值定義一個枚舉

public enum HeightTypes
{
    Tall,
    Short
}

然后將其用作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; }
}

現在,當您擁有 Meta class 的實例時,您可以僅將其 Height 屬性設置為 Tall 或 Short:

var meta = new Meta();
meta.Height = HeightTypes.Tall;

定義一個枚舉。

public Enum Heights
{
    Tall,
    Short
}

然后將您的屬性定義為枚舉類型

public Heights Height { get; set; }

有關詳細信息,請參閱http://msdn.microsoft.com/en-us/library/system.enum.aspx

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM