문제

Given the following function;

void SomeFunction<T>(...){
    SomeOtherFunction<T>();
}

This works fine, but sometimes the function fails before T passed is an array type, but it mustn't be an array type. These functions have to do with JSON deserialization of a dictionary, but for some reason it doesn't accept the T array argument when the dictionary has only one entry.

In short, I want to do this

void SomeFunction<T>(...){
    try {
    SomeOtherFunction<T>();
    } catch ( Exception e ){
        SomeOtherFunction<T arrayless>();
    }
}

I've tried a ton of stuff, and I realize the real problem is somewhere else, but I need to temporary fix this so I can work on a real solution in the deserializer. I tried reflection too using the following method;

MethodInfo method = typeof(JToken).GetMethod("ToObject", System.Type.EmptyTypes);
MethodInfo generic = method.MakeGenericMethod(typeof(T).GetElementType().GetGenericTypeDefinition());
object result = generic.Invoke(valueToken, null);

But that doesn't quite work either.

Thank you!

도움이 되었습니까?

해결책

I am not really sure what you are trying to achieve here, but to get the type of the elements in an array, you have to use Type.GetElementType():

void SomeFunction<T>()
{
    var type = typeof(T);
    if(type.IsArray)
    {
        var elementType = type.GetElementType();
        var method = typeof(Foo).GetMethod("SomeOtherFunction")
                                .MakeGenericMethod(elementType);
        // invoke method
    }
    else
        foo.SomeOtherFunction<T>(...);
}

다른 팁

If I follow you correctly, you want to call one of two generic functions depending on whether the type of the object is an array or not.

How about:

if (typeof(T).ImplementsInterface(typeof(IEnumerable)))
    someFunction<T>();
else
    someOtherFunction<T>();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top