C #에서 여러 열거 형 값을 어떻게 전달합니까?
때로는 다른 사람의 C # 코드를 읽을 때 단일 매개 변수에 여러 열거 형 값을 허용하는 메서드가 표시됩니다. 나는 항상 그것이 깔끔하다고 생각했지만 결코 들여다 보지 않았습니다.
글쎄, 지금 나는 그것을 필요로 할 것 같지만 어떻게 해야할지 모르겠다.
- 이것을 받아들이도록 메소드 서명을 설정하십시오.
- 방법의 값으로 작업
- 열거 형을 정의
이런 종류의 일을 달성하기 위해.
특정 상황에서 System.DayOfWeek를 사용하고 싶습니다.
[Serializable]
[ComVisible(true)]
public enum DayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6
}
하나 이상의 DayOfWeek 값을 내 메소드에 전달할 수 있기를 원합니다. 이 특정 열거 형을 그대로 사용할 수 있습니까? 위에 나열된 3 가지를 어떻게합니까?
열거 형을 정의 할 때 [Flags]로 속성을 지정하고 값을 2의 거듭 제곱으로 설정하면이 방식으로 작동합니다.
함수에 여러 값을 전달하는 것 외에 다른 것은 없습니다.
예를 들면 다음과 같습니다.
[Flags]
enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public void RunOnDays(DaysOfWeek days)
{
bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;
if (isTuesdaySet)
//...
// Do your work here..
}
public void CallMethodWithTuesdayAndThursday()
{
this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}
자세한 내용 은 열거 형에 대한 MSDN 설명서를 참조하십시오 .
추가 된 질문에 대한 답변으로 수정하십시오.
array / collection / params 배열로 전달하는 것과 같은 것을 원하지 않으면 해당 열거 형을 그대로 사용할 수 없습니다. 여러 값을 전달할 수 있습니다. flags 구문을 사용하려면 Enum을 플래그로 지정해야합니다 (또는 언어가 의도하지 않은 방식으로 언어를 개성화해야 함).
더 우아한 해결책은 HasFlag ()를 사용하는 것입니다.
[Flags]
public enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public void RunOnDays(DaysOfWeek days)
{
bool isTuesdaySet = days.HasFlag(DaysOfWeek.Tuesday);
if (isTuesdaySet)
{
//...
}
}
public void CallMethodWithTuesdayAndThursday()
{
RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}
두 번째 리드의 대답입니다. 그러나 열거 형을 만들 때 일종의 비트 필드를 만들도록 각 열거 형 멤버에 대한 값을 지정해야합니다. 예를 들면 다음과 같습니다.
[Flags]
public enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64,
None = 0,
All = Weekdays | Weekend,
Weekdays = Monday | Tuesday | Wednesday | Thursday | Friday,
Weekend = Sunday | Saturday,
// etc.
}
내 특정 상황에서 System.DayOfWeek를 사용하고 싶습니다.
You can not use the System.DayOfWeek as a [Flags]
enumeration because you have no control over it. If you wish to have a method that accepts multiple DayOfWeek
then you will have to use the params
keyword
void SetDays(params DayOfWeek[] daysToSet)
{
if (daysToSet == null || !daysToSet.Any())
throw new ArgumentNullException("daysToSet");
foreach (DayOfWeek day in daysToSet)
{
// if( day == DayOfWeek.Monday ) etc ....
}
}
SetDays( DayOfWeek.Monday, DayOfWeek.Sunday );
Otherwise you can create your own [Flags]
enumeration as outlined by numerous other responders and use bitwise comparisons.
[Flags]
public enum DaysOfWeek
{
Mon = 1,
Tue = 2,
Wed = 4,
Thur = 8,
Fri = 16,
Sat = 32,
Sun = 64
}
You have to specify the numbers, and increment them like this because it is storing the values in a bitwise fashion.
Then just define your method to take this enum
public void DoSomething(DaysOfWeek day)
{
...
}
and to call it do something like
DoSomething(DaysOfWeek.Mon | DaysOfWeek.Tue) // Both Monday and Tuesday
To check if one of the enum values was included check them using bitwise operations like
public void DoSomething(DaysOfWeek day)
{
if ((day & DaysOfWeek.Mon) == DaysOfWeek.Mon) // Does a bitwise and then compares it to Mondays enum value
{
// Monday was passed in
}
}
[Flags]
public enum DaysOfWeek{
Sunday = 1 << 0,
Monday = 1 << 1,
Tuesday = 1 << 2,
Wednesday = 1 << 3,
Thursday = 1 << 4,
Friday = 1 << 5,
Saturday = 1 << 6
}
call the method in this format
MethodName(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
Implement a EnumToArray method to get the options passed
private static void AddEntryToList(DaysOfWeek days, DaysOfWeek match, List<string> dayList, string entryText) {
if ((days& match) != 0) {
dayList.Add(entryText);
}
}
internal static string[] EnumToArray(DaysOfWeek days) {
List<string> verbList = new List<string>();
AddEntryToList(days, HttpVerbs.Sunday, dayList, "Sunday");
AddEntryToList(days, HttpVerbs.Monday , dayList, "Monday ");
...
return dayList.ToArray();
}
Mark your enum with the [Flags] attribute. Also ensure that all of your values are mutually exclusive (two values can't add up to equal another) like 1,2,4,8,16,32,64 in your case
[Flags]
public enum DayOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
When you have a method that accepts a DayOfWeek enum use the bitwise or operator (|) to use multiple members together. For example:
MyMethod(DayOfWeek.Sunday|DayOfWeek.Tuesday|DayOfWeek.Friday)
To check if the parameter contains a specific member, use the bitwise and operator (&) with the member you are checking for.
if(arg & DayOfWeek.Sunday == DayOfWeek.Sunday)
Console.WriteLine("Contains Sunday");
Reed Copsey is correct and I would add to the original post if I could, but I cant so I'll have to reply instead.
Its dangerous to just use [Flags] on any old enum. I believe you have to explicitly change the enum values to powers of two when using flags, to avoid clashes in the values. See the guidelines for FlagsAttribute and Enum.
With the help of the posted answers and these:
- FlagsAttribute Class (Look at the comparison of using and not using the [Flags] attribute)
- Enum Flags Attribute
I feel like I understand it pretty well.
Thanks.
Something of this nature should show what you are looking for:
[Flags]
public enum SomeName
{
Name1,
Name2
}
public class SomeClass()
{
public void SomeMethod(SomeName enumInput)
{
...
}
}
참고URL : https://stackoverflow.com/questions/1030090/how-do-you-pass-multiple-enum-values-in-c
'programing tip' 카테고리의 다른 글
런타임시 Android보기 크기 결정 (0) | 2020.07.28 |
---|---|
최대 절전 모드의 경량 대안? (0) | 2020.07.28 |
숭고한 텍스트 편집기에서 개요보기를 얻는 방법은 무엇입니까? (0) | 2020.07.28 |
프로그램의 실행 시간을 계산하는 방법은 무엇입니까? (0) | 2020.07.28 |
BroadcastReceiver.onReceive는 항상 UI 스레드에서 실행됩니까? (0) | 2020.07.28 |