Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

c# - Why would someone use the << operator in an enum declaration?

I was looking at the code I have currently in my project and found something like this:

public enum MyEnum
{
    open     = 1 << 00,
    close    = 1 << 01,
    Maybe    = 1 << 02,
    ........
}

The << operand is the shift operand, which shifts the first operand left by the number bits specified in the second operand.

But why would someone use this in an enum declaration?

question from:https://stackoverflow.com/questions/17888141/why-would-someone-use-the-operator-in-an-enum-declaration

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This allows you to do something like this:

var myEnumValue = MyEnum.open | MyEnum.close;

without needing to count bit values of multiples of 2.

(like this):

public enum MyEnum
{
    open     = 1,
    close    = 2,
    Maybe    = 4,
    ........
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...