The code that I have so far is as follows: I want to decide to get rid of try-catch:
public static bool IsNeverValidGenericArgument(this Type type) { var elementType=type.GetElementType(); if(null!=elementType) { if(type.IsArray) try { typeof(IList<>).MakeGenericType(elementType); return false; } catch(ArgumentException) { } catch(TypeLoadException) { } return true; // pointer or byref } return typeof(void)==type||typeof(RuntimeArgumentHandle)==type || typeof(ArgIterator)==type||typeof(TypedReference)==type; }
I'm trying to write dynamic type building code, and my code will call GetInterfaces() for each type passed, but some of the types passed by consumer code can TypeLoadException in RuntimeType internally (e.g. typeof(ArgIterator).MakeArrayType().MakeArrayType() in 3.5, but not 4.0+), I need to check if it is never a valid general argument. trap attempts, but nothing good.
Please note that the cases that he throws may vary in different versions of the .Net framework .
Edit:
Alternative method:
public static bool IsNeverValidGenericArgument(this Type type) { var elementType=type.GetElementType(); if(null!=elementType) { if(type.IsArray) return elementType.IsNeverValidGenericArgument(); return true; // pointer or byref } return typeof(void)==type||typeof(RuntimeArgumentHandle)==type || typeof(ArgIterator)==type||typeof(TypedReference)==type; }
But this will report some types as invalid, which in fact would not be the cause of the exception in RuntimeType , for example typeof(ArgIterator).MakeArrayType(2).MakeArrayType() .
I know that some types are not nominated, but I cannot avoid their use in consumer code.
Ken kin
source share