How to create a general method for getting enumeration elements in a ushort object

The idea is to perform the bit-test ushortprovided , find any and all matches inside enum collection.

The code I developed looks like this:

public List<T> GetEnumItemsFromUshort<T>(ushort input) where T : struct, IComparable, IConvertible, IFormattable
    {
        var output = new List<T>();
        foreach (T enumValue in Enum.GetValues(typeof(T)))
        {
            if ((input & enumValue.ToUInt16(new CultureInfo("en-US"))) == enumValue.ToUInt16(new CultureInfo("en-US")))
            {
                output.Add(enumValue);
            }
        }
        return output;
    }

As you can see, I use a generic type to determine the return type.

I searched the site and found that a general type restriction with the following struct, IComparable, IConvertible, IFormattablebehaves like enum.

The code generates a list of listings provided to the list containing the matches found.

Then he proceeds to scan the input value to find all and all the elements that were masked (bitwise operation, as indicated above) correspond.

, .

, , , , , .

+4

Source: https://habr.com/ru/post/1616215/


All Articles