开发者

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

开发者 https://www.devze.com 2023-03-19 00:02 出处:网络
I have a class like this: 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. What I would like is for the Height t

I have a class like this:

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. 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 defa开发者_Go百科ult to "Short" in the constructor. 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.)

You need the validation because enums are really just differently-typed integer values. 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:

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:

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号