5 回答

TA貢獻1804條經驗 獲得超8個贊
我想要實現的只是“如果參數中只有一個值,則做某事,否則,如果有多個值,則做其他事情”。
由于Flags值中是單個位,因此是 2 的冪,因此您可以使用
uint v; // we want to see if v is a power of 2
bool f; // the result goes here?
f = (v & (v - 1)) == 0;
檢查該值是否為 2 的冪,如果不是,則設置了多個標志。
但請記住這一點
請注意,此處 0 被錯誤地視為 2 的冪。
public static void dummy(days Daysofweek)
{
? ? int val = (int) Daysofweek;
? ? bool hasMultipleFlagsSet = val != 0 && (val & (val - 1)) == 0;
? ? if(hasMultipleFlagsSet){/*some function*/}
? ? else {/*some other? function*/}
? ? Console.WriteLine(Daysofweek.ToString());
}

TA貢獻1862條經驗 獲得超6個贊
這是一個通用的解決方案:
public static int CountFlags( Enum days )
{
? ? int flagsSet = 0;
? ? foreach( var value in Enum.GetValues( days.GetType() ) )
? ? {
? ? ? ? if( days.HasFlag( (Enum)value ) )
? ? ? ? {
? ? ? ? ? ? ++flagsSet;
? ? ? ? }
? ? }
? ? return flagsSet;
}

TA貢獻1936條經驗 獲得超7個贊
使用HasFlag
using System;
[Flags] public enum Pets {
? ?None = 0,
? ?Dog = 1,
? ?Cat = 2,
? ?Bird = 4,
? ?Rabbit = 8,
? ?Other = 16
}
public class Example
{
? ?public static void Main()
? ?{
? ? ? Pets[] petsInFamilies = { Pets.None, Pets.Dog | Pets.Cat, Pets.Dog };
? ? ? int familiesWithoutPets = 0;
? ? ? int familiesWithDog = 0;
? ? ? foreach (var petsInFamily in petsInFamilies)
? ? ? {
? ? ? ? ?// Count families that have no pets.
? ? ? ? ?if (petsInFamily.Equals(Pets.None))
? ? ? ? ? ? familiesWithoutPets++;
? ? ? ? ?// Of families with pets, count families that have a dog.
? ? ? ? ?else if (petsInFamily.HasFlag(Pets.Dog))
? ? ? ? ? ? familiesWithDog++;
? ? ? }
? ? ? Console.WriteLine("{0} of {1} families in the sample have no pets.",?
? ? ? ? ? ? ? ? ? ? ? ? familiesWithoutPets, petsInFamilies.Length);? ?
? ? ? Console.WriteLine("{0} of {1} families in the sample have a dog.",?
? ? ? ? ? ? ? ? ? ? ? ? familiesWithDog, petsInFamilies.Length);? ?
? ?}
}
// The example displays the following output:
//? ? ? ?1 of 3 families in the sample have no pets.
//? ? ? ?2 of 3 families in the sample have a dog.

TA貢獻1811條經驗 獲得超4個贊
轉換為整數,然后計算設置為 1 的位數:
public enum DAYS
{
sunday =1,
monday =2,
tuesday= 4
}
static void Main(string[] args)
{
DAYS days = DAYS.sunday | DAYS.monday;
int numDays = CountDays(days);
}
static int CountDays(DAYS days)
{
int number = 0;
for(int i = 0; i < 32; i++)
{
number += ((uint)days & (1 << i)) == 0 ? 0 : 1;
}
return number;
}

TA貢獻1810條經驗 獲得超4個贊
我想要實現的只是“如果參數中只有一個值,則做某事,否則,如果有多個值,則做其他事情”。
假設您沒有向枚舉添加任何“組合”命名值(例如,您沒有Weekend
預先設置為 的成員Sunday|Saturday
),您可以使用Enum.GetName
對于枚舉的命名成員以及null
多個成員的任意組合,它將返回一個非空字符串。
- 5 回答
- 0 關注
- 201 瀏覽
添加回答
舉報