2015-01-22 4 views
1

.NET에서 C#으로 양식 설정을로드하기위한 일반적인 방법을 시도합니다. 각 설정에는 자체 try try 블록이 포함되어 있습니다 (단 하나가 아닌 다른 설정으로 진행). 유효한). 그러나 개체에 appsetting 할당에 대한 해결 방법을 알아낼 수는 없습니다. comipler는 내가 암시 적으로 객체의 유형을 형 변환하는 것을 허용하지 않습니다.은 암시 적으로 System.Type을 객체로 변환 할 수 없습니다.

private void LoadFormSettings(object o) 
{ 
    try 
    { 
    //Load settings when application is started 
    Type t = o.GetType(); 

    // Operator '<' cannot be applied to operands of type 'method group' and 'System.Type' 
    o = getAppSetting<o.GetType()>("Setting"); 
    // Cannot implicitly convert type 't' to 'object' 
    o = getAppSetting<t>("Setting"); 
    // The type arguments for method... cannot be inferred from the usage. Try specifying the type arguments explicitly 
    o = getAppSetting("Setting"); 
    } 
    catch (Exception ee) 
    { 
    } 
} 

private T getAppSetting<T>(string key) 
{ 
    string value = config.AppSettings.Settings[key].Value; 
    if (typeof(T) == typeof(Point)) 
    { 
    string[] values = value.Split(','); 
    return (T) Convert.ChangeType(value, typeof(T)); 
    } 
} 
+0

런타임시 알려진 값인 'Type' 클래스의 인스턴스를 제네릭 매개 변수로 사용할 수 없습니다 (컴파일 타임에 알려줘야 함). 대신에 일반 메소드를 만들 수 있습니다. – CodesInChaos

+0

예외 처리 패턴은 좋은 생각이 아닙니다. 1) 기대하는 것뿐만 아니라 모든 예외를 포착하고 있습니다. 2) 예를 들어'TryParse'를 사용하여 예외를 throw하지 않도록합니다. – CodesInChaos

답변

1

Typet이 인스턴스입니다. 일반에는 인스턴스 대신 유형이 필요합니다. F<t>() 대신 F<Type>()으로 쓸 수 있습니다. 귀하의 경우에는 더 나은 작성

+0

고맙습니다. 작동합니다. 나는이 옵션을 생각하지 않았다. – Almis

관련 문제