1

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!

4

2 回答 2

2

我不确定您要在这里实现什么,但是要获取数组中元素的类型,您必须使用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>(...);
}
于 2013-07-09T11:03:13.447 回答
0

如果我正确地跟随你,你想根据对象的类型是否是数组来调用两个通用函数之一。

怎么样:

if (typeof(T).ImplementsInterface(typeof(IEnumerable)))
    someFunction<T>();
else
    someOtherFunction<T>();
于 2013-07-09T10:59:25.337 回答