문자열 값이 열거 형 목록에 있는지 확인하는 방법은 무엇입니까?
내 쿼리 문자열에는 연령 변수가 ?age=New_Born
있습니다.
이 문자열 값 New_Born
이 내 Enum 목록에 있는지 확인할 수있는 방법이 있습니까?
[Flags]
public enum Age
{
New_Born = 1,
Toddler = 2,
Preschool = 4,
Kindergarten = 8
}
지금은 if 문을 사용할 수 있지만 Enum 목록이 커지면 사용할 수 있습니다. 더 나은 방법을 찾고 싶습니다. 나는 Linq를 사용하려고 생각하고 있지만 어떻게 해야할지 모르겠습니다.
당신이 사용할 수있는:
Enum.IsDefined(typeof(Age), youragevariable)
Enum.TryParse 메서드를 사용할 수 있습니다.
Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
// You now have the value in age
}
성공하면 true를 반환 하는 TryParse 메서드를 사용할 수 있습니다 .
Age age;
if(Enum.TryParse<Age>("myString", out age))
{
//Here you can use age
}
이것이 오래된 스레드라는 것을 알고 있지만 Enumerates의 속성을 사용하는 약간 다른 접근 방식과 일치하는 enumerate를 찾는 도우미 클래스가 있습니다.
이렇게하면 단일 열거에 여러 매핑을 가질 수 있습니다.
public enum Age
{
[Metadata("Value", "New_Born")]
[Metadata("Value", "NewBorn")]
New_Born = 1,
[Metadata("Value", "Toddler")]
Toddler = 2,
[Metadata("Value", "Preschool")]
Preschool = 4,
[Metadata("Value", "Kindergarten")]
Kindergarten = 8
}
이런 내 도우미 클래스로
public static class MetadataHelper
{
public static string GetFirstValueFromMetaDataAttribute<T>(this T value, string metaDataDescription)
{
return GetValueFromMetaDataAttribute(value, metaDataDescription).FirstOrDefault();
}
private static IEnumerable<string> GetValueFromMetaDataAttribute<T>(T value, string metaDataDescription)
{
var attribs =
value.GetType().GetField(value.ToString()).GetCustomAttributes(typeof (MetadataAttribute), true);
return attribs.Any()
? (from p in (MetadataAttribute[]) attribs
where p.Description.ToLower() == metaDataDescription.ToLower()
select p.MetaData).ToList()
: new List<string>();
}
public static List<T> GetEnumeratesByMetaData<T>(string metadataDescription, string value)
{
return
typeof (T).GetEnumValues().Cast<T>().Where(
enumerate =>
GetValueFromMetaDataAttribute(enumerate, metadataDescription).Any(
p => p.ToLower() == value.ToLower())).ToList();
}
public static List<T> GetNotEnumeratesByMetaData<T>(string metadataDescription, string value)
{
return
typeof (T).GetEnumValues().Cast<T>().Where(
enumerate =>
GetValueFromMetaDataAttribute(enumerate, metadataDescription).All(
p => p.ToLower() != value.ToLower())).ToList();
}
}
그런 다음 다음과 같이 할 수 있습니다.
var enumerates = MetadataHelper.GetEnumeratesByMetaData<Age>("Value", "New_Born");
And for completeness here is the attribute:
[AttributeUsage(AttributeTargets.Field, Inherited = false, AllowMultiple = true)]
public class MetadataAttribute : Attribute
{
public MetadataAttribute(string description, string metaData = "")
{
Description = description;
MetaData = metaData;
}
public string Description { get; set; }
public string MetaData { get; set; }
}
I've got a handy extension method that uses TryParse, as IsDefined is case-sensitive.
public static bool IsParsable<T>(this string value) where T : struct
{
return Enum.TryParse<T>(value, true, out _);
}
You should use Enum.TryParse to achive your goal
This is a example:
[Flags]
private enum TestEnum
{
Value1 = 1,
Value2 = 2
}
static void Main(string[] args)
{
var enumName = "Value1";
TestEnum enumValue;
if (!TestEnum.TryParse(enumName, out enumValue))
{
throw new Exception("Wrong enum value");
}
// enumValue contains parsed value
}
To parse the age:
Age age;
if (Enum.TryParse(typeof(Age), "New_Born", out age))
MessageBox.Show("Defined"); // Defined for "New_Born, 1, 4 , 8, 12"
To see if it is defined:
if (Enum.IsDefined(typeof(Age), "New_Born"))
MessageBox.Show("Defined");
Depending on how you plan to use the Age
enum, flags may not be the right thing. As you probably know, [Flags]
indicates you want to allow multiple values (as in a bit mask). IsDefined
will return false for Age.Toddler | Age.Preschool
because it has multiple values.
참고URL : https://stackoverflow.com/questions/10804102/how-to-check-if-string-value-is-in-the-enum-list
'programing tip' 카테고리의 다른 글
<and> 내부 탈출 방법 (0) | 2020.09.22 |
---|---|
마스터를 Github에 Git-push 할 수 없음- 'origin'이 git 저장소로 표시되지 않음 / 권한 거부 됨 (0) | 2020.09.22 |
virtualenv와 함께 pip를 사용할 때 "Permission denied"를 방지하는 방법 (0) | 2020.09.21 |
postgresql 목록 및 크기별 주문 테이블 (0) | 2020.09.21 |
HTTP 301과 308 상태 코드의 차이점은 무엇입니까? (0) | 2020.09.21 |