mercredi 4 novembre 2020

Is there a way to avoid this switch-case block via the use of Expression trees?

Is there a way to avoid the following switch-case block via the use of expression trees? If so, how?

switch(value)
{
    case Test1 a:
        return GenericClass<Test1>.IsValid(a);
    case Test2 b:
        return GenericClass<Test2>.IsValid(b);
    case Test3 c: 
        return GenericClass<Test3>.IsValid(c);
    case Test4 d: 
        return GenericClass<Test4>.IsValid(d);
    case Test5 e: 
        return GenericClass<Test5>.IsValid(e);
    case Test6 f: 
        return GenericClass<Test6>.IsValid(f);
    case Test7 g: 
        return GenericClass<Test7>.IsValid(g);
    case Test8 h: 
        return GenericClass<Test8>.IsValid(h);
    case Test9 i:
        return GenericClass<Test9>.IsValid(i);
    case Test10 j:
        return GenericClass<Test10>.IsValid(j);
    default:
        return false;

}

We're basically accessing the same generic class. The only difference is its generic type, and the object it receives (it must match that generic type).

value is boxed in a object, hence why the long switch-case block approach.

EDIT: If it would make things easier, though doubtfully faster, we can change the definition of IsValid to accept an object type.





Aucun commentaire:

Enregistrer un commentaire