2011-06-14 2 views
3

문자열에서 열거를 구문 분석하는 데 이상한 질문이 있습니다. 그대로, 내 애플 리케이션은 설정 파일에서 몇 가지 열거의 구문 분석을 처리해야합니다. 그러나 각 열거 형에 구문 분석 루틴을 쓰지 않으려합니다 (많은 경우).C#의 일반 열거 형 문자열 값 파서?

내가 직면하고있는 문제는 다음 코드가 이상한 오류를 보이고 있다는 것입니다. T의 유형은 null이 아닌 값 유형 또는 일종의 정렬이어야합니다. 열거 형은 기본적으로 nullable이 아닌 것으로 생각했습니다.

where T : enum을 사용하여 T의 유형을 제한하면 메소드 본문 (if Enum.TryParse 문 제외)의 모든 항목에 오류로 밑줄이 그어집니다.

누구든지이 이상한 소소한 문제를 해결할 수 있습니까?

을 :

감사합니다, 마틴

public static T GetConfigEnumValue<T>(NameValueCollection config, 
             string configKey, 
             T defaultValue) // where T : enum ? 
{ 
    if (config == null) 
    { 
     return defaultValue; 
    } 

    if (config[configKey] == null) 
    { 
     return defaultValue; 
    } 

    T result = defaultValue; 
    string configValue = config[configKey].Trim(); 

    if (string.IsNullOrEmpty(configValue)) 
    { 
     return defaultValue; 
    } 

    //Gives me an Error - T has to be a non nullable value type? 
    if(! Enum.TryParse<T>(configValue, out result)) 
    { 
     result = defaultValue; 
    } 

    //Gives me the same error: 
    //if(! Enum.TryParse<typeof(T)>(configValue, out result)) ... 

    return result; 
} 

오류의 텍스트를 게시하도록 요청 사용자를 그래서 여기 간다, (이 코드 시간입니다,/런타임 컴파일되지 않음) 유형 'T'는 일반 유형 또는 메소드 'System.Enum.TryParse (string, out TEnum)'에서 TEnum 매개 변수로 사용하기 위해 nullable이 아닌 값 유형이어야합니다.

+0

이 오류를 부착 할 수 있습니까? where 조건없이 코드가 작동해야하는 것처럼 보입니다. –

+0

'T : struct' –

+0

@ jdv-Jan de Vaan도이 작업을 수행해보십시오. 내 말은 열거 형은 int 형이고 int 형은 System.Int32 형이라는 것입니다. 그러나 실제로 작동합니까? – bleepzter

답변

1
public static T GetConfigEnumValue<T>(NameValueCollection config, string configKey, T defaultValue) 
{ 
    if (config == null) 
    { 
     return defaultValue; 
    } 

    if (config[configKey] == null) 
    { 
     return defaultValue; 
    } 

    T result = defaultValue; 
    string configValue = config[configKey].Trim(); 

    if (string.IsNullOrEmpty(configValue)) 
    { 
     return defaultValue; 
    } 

    try 
    { 
     result = (T)Enum.Parse(typeof(T), configValue, true); 
    } 
    catch 
    { 
     result = defaultValue; 
    } 

    return result; 
} 
0

C#에서는 where T : enum을 사용할 수 없기 때문에 where T : struct을 사용해야합니다.

Michael 제안 된 제한 사항을 해결할 수있는 방법이 있습니다.

1

답 찾을 수 있습니다.

그래서 같은 방식에 제네릭 제약 조건을 넣어 :

public static T GetConfigEnumValue<T>(NameValueCollection config, 
             string configKey, 
             T defaultValue) // where T : ValueType 

또는 단지 Enum.TryParse 방법에 같은 제약 조건을 배치합니다.

where T : struct, new() 

여기이 정의를 찾을 수 있습니다

http://msdn.microsoft.com/en-us/library/dd783499.aspx

+0

'T : ValueType'은 작동하지 않고'ValueType'은 nullable이며'where T : struct'가되어야합니다. –