简体   繁体   中英

Bit operations on Enum

I'm having some problems with the following:

  • I want to get the first visible AND frozen column of a column collection.

I think this will do it:

DataGridViewColumnCollection dgv = myDataGridView.Columns;
dgv.GetFirstColumn(
     DataGridViewElementStates.Visible | DataGridViewElementStates.Frozen);
  • Is it also possible to make a bitmask to get the first frozen OR visible column?

The implementation is, AFAIK, "all of these" - it uses:

((this.State & elementState) == elementState);

Which is "all of". If you wanted to write an "any of", perhaps add a helper method: (add the "this" before DataGridViewColumnCollection to make it a C# 3.0 extension method in)

    public static DataGridViewColumn GetFirstColumnWithAny(
        DataGridViewColumnCollection columns, // optional "this"
        DataGridViewElementStates states)
    {
        foreach (DataGridViewColumn column in columns)
        {
            if ((column.State & states) != 0) return column;
        }
        return null;
    }

Or with LINQ:

        return columns.Cast<DataGridViewColumn>()
            .FirstOrDefault(col => (col.State & states) != 0);

Well, bitmasks usually work like this:

| is joining flags up. & is filtering subset of flags from a flag set represented by a bitmask. ^ is flipping flags by a mask (at least in C/C++).

To get the first frozen OR visible column GetFirstColumn must handle bitmasks different way (eg GetFirstColumn could get the first column that matches any of the flags set, but this is not the case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM