基于泛型类型参数和C#的条件代码

zed*_*zed 0 c# asp.net-mvc types

我在C#中有一个方法,它接收一个泛型类型作为参数:

private void DoSomething<T>(T param)
{
    //...
}
Run Code Online (Sandbox Code Playgroud)

我需要根据具体类型执行不同的操作param.我知道我可以用几句if话来实现它,像这样:

private void DoSomething<T>(T param)
{
    if (param is TypeA)
    {
        // do something specific to TypeA case

    } else if (param is TypeB)
    {
        // do something specific to TypeB case

    } else if ( ... )
    {
        ...
    }

    // ... more code to run no matter the type of param
}
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法呢?也许还有switch-case其他方法,我不知道?

小智 5

只需使用重载而不是泛​​型.