基于带有C#的泛型类型参数的条件代码 [英] Conditional code based on generic type parameter with C#

查看:52
本文介绍了基于带有C#的泛型类型参数的条件代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a method in C# which receives a generic type as argument:

private void DoSomething<T>(T param)
{
    //...
}

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

I need to perform different things depending on what type is param of. I know I can achieve it with several if sentences, like this:

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
}

是否有更好的方法?也许使用 switch-case 或其他我不知道的方法?

Is there a better way of doing this? Maybe with switch-case or another approach that I'm not aware of?

推荐答案

您可以为特定类型创建特定方法.

You can create a specific method for a particular type.

    private void DoSomething<T>(T param)
    {
        //...
    }

    private void DoSomething(int param) { /* ... */ }

    private void DoSomething(string  param) { /* ... */ }

这篇关于基于带有C#的泛型类型参数的条件代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆