2013-07-04 2 views
0

MyFaultBase에서 파생 된 다양한 클래스가있는 경우를 생각해보십시오. 따라서 웹 서비스가 오류를 나타낼 필요가있을 때는 FaultException<MySpecificFault> 예외를 throw합니다.일반 클래스에서 사용하는 유형을 확인하는 방법

이 예외가 발생하면 FaultException<T>MyFaultBase에서 파생 된 클래스에 바인딩되는지 여부를 어떻게 결정할 수 있습니까?

답변

3

:

public class SpecificClass : BaseClass 
    { 
    } 

    public class BaseClass 
    { 
    } 

    public class TemplatedClass<T> 
    { 
    } 

    static void Main(string[] args) 
    { 
     var templateInstance = new TemplatedClass<SpecificClass>(); 
     var @true = typeof (BaseClass).IsAssignableFrom(templateInstance.GetType().GetGenericArguments()[0]); 

     var templateInstance2 = new TemplatedClass<int>(); 
     var @false = typeof (BaseClass).IsAssignableFrom(templateInstance2.GetType().GetGenericArguments()[0]); 
    } 
0

내가 알 수있는 한, 일반적인 클래스를 확인하는 간단한 방법은 없습니다. 이는 일반적인 매개 변수의 유연성 때문일 수 있습니다. 여기에 솔루션입니다 :

public static bool IsExceptionBoundToType(FaultException fe, Type checkType) 
{ 
    bool isBound = false; 

    // Check to see if the FaultException is a generic type. 
    Type feType = fe.GetType(); 
    if (feType.IsGenericType && feType.GetGenericTypeDefinition() == typeof(FaultException<>)) 
    { 
     // Check to see if the Detail property is a class of the specified type. 
     PropertyInfo detailProperty = feType.GetProperty("Detail"); 
     if (detailProperty != null) 
     { 
     object detail = detailProperty.GetValue(fe, null); 
     isBound = checkType.IsAssignableFrom(detail.GetType()); 
     } 
    } 

    return (isBound); 
} 

캐치를 제외하고 다음과 같이 그것을 확인 : 글로벌 방법으로

catch (Exception ex) 
{ 
    if ((ex is FaultException) && IsExceptionBoundToType(ex, typeof(MyFaultBase))) 
    { 
     // do something 
    } 
} 
2

당신은 Type.GetGenericArguments()를 사용하여 제네릭 형식 인수를 얻을 수 있습니다.

public static bool IsExceptionBoundToType(FaultException fe, Type checkType) 
{ 
    bool isBound = false; 
    Type feType = fe.GetType(); 
    if (feType.IsGenericType && feType.GetGenericTypeDefinition() == typeof(FaultException<>)) 
    { 
     Type faultType = feType.GetGenericArguments()[0]; 
     isBound = checkType.IsAssignableFrom(faultType); 
    } 

    return isBound; 
} 
:

그런 다음 IsExceptionBoundToType 방법은 다음과 같이 보일 수 있습니다

관련 문제