How to call a generic method with type constraints when the parameter doesn't have these constraints?

StackOverflow https://stackoverflow.com/questions/15808370

  •  01-04-2022
  •  | 
  •  

Вопрос

class A { }
interface I { }
void GenericStuff<T>(T x) { }
void SpecificStuff<T>(T x) where T : A, I { }

void Start<T>(T x)
{
    if (x is A && x is I)
        SpecificStuff(x); // <---- Wrong type
    else
        GenericStuff(x);
}

I've got the situation illustrated above. In method Start() I get a single parameter x and depending on it's type I want to call either the GenericStuff() or the SpecificStuff() method. Naturally, the type constraints prevent me from doing so, and since there are two of them, I cannot get around them by casting.

Is there any way (short of reflection) to accomplish this?

Это было полезно?

Решение

You can use dynamic. While this is more or less glorified reflection, it looks much nicer:

void Start<T>(T x)
{
    if (x is A && x is I)
        SpecificStuff((dynamic)x);
    else
        GenericStuff(x);
}

Please note:
If, at a later point, you change the type constraints of SpecificStuff to contain a third interface and you forget to update your if accordingly, you will get runtime exceptions and not compile time errors.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top