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