What do two left-angle brackets “<<” mean in C#?

前端 未结 15 1935
长情又很酷
长情又很酷 2020-12-12 13:55

Basically the questions in the title. I\'m looking at the MVC 2 source code:

[Flags]
public enum HttpVerbs {
    Get = 1 << 0,
    Post = 1 << 1,         


        
15条回答
  •  囚心锁ツ
    2020-12-12 14:11

    Previous answers have explained what it does, but nobody seems to have taken a guess as to why. It seems quite likely to me that the reason for this code is that the loop is iterating over each possible combination of members of a list -- this is the only reason I can see why you would want to iterate up to 2^{list.Count}. The variable i would therefore be badly named: instead of an index (which is what I usually interpret 'i' as meaning), its bits represent a combination of items from the list, so (for example) the first item may be selected if bit zero of i is set ((i & (1 << 0)) != 0), the second item if bit one is set ((i & (1 << 1)) != 0) and so on. 1 << list.Count is therefore the first integer that does not correspond to a valid combination of items from the list, as it would indicate selection of the non-existant list[list.Count].

提交回复
热议问题