C# 泛型和类型检查

标签 c# generics types

我有一个使用 IList<T> 的方法作为参数。我需要检查那个 T 的类型对象是并基于它做一些事情。我正在尝试使用 T值,但编译器不允许。我的解决方案如下:

private static string BuildClause<T>(IList<T> clause)
{
    if (clause.Count > 0)
    {
        if (clause[0] is int || clause[0] is decimal)
        {
           //do something
        }
        else if (clause[0] is String)
        {
           //do something else
        }
        else if (...) //etc for all the types
        else
        {
           throw new ApplicationException("Invalid type");
        }
    } 
}

必须有更好的方法来做到这一点。有什么方法可以检查 T 的类型吗?传入然后使用 switch声明?

最佳答案

你可以使用重载:

public static string BuildClause(List<string> l){...}

public static string BuildClause(List<int> l){...}

public static string BuildClause<T>(List<T> l){...}

或者您可以检查泛型参数的类型:

Type listType = typeof(T);
if(listType == typeof(int)){...}

关于C# 泛型和类型检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/982952/

相关文章:

c# - Serilog 不向 Elasticsearch 8 发送日志

c# - 有没有在 XAML 中整合类似的数据绑定(bind)和/或触发器?

c# - XmlDocument 存在于哪个程序集中,以及如何使用它?

c# - 基本类型和继承类型的工作通用列表

generics - 以通用方式操作 Scala 集合

haskell - 实现相同功能的不同类型的映射列表?

c++ - 不同编译器中的指针大小

c# - 多个自动映射器命名约定

c# - 使用反射从 Type 获取类并在 C# 中使用 Type 调用泛型构造函数

c# - 我怎么知道项目在枚举中?