【发布时间】:2010-11-02 05:57:43
【问题描述】:
我有一个使用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 语句?
【问题讨论】:
-
我个人想知道您对每种数据类型都做了什么特别的事情。如果您对每种数据类型进行大致相同的转换,则将不同类型映射到一个通用接口并在该接口上操作可能会更容易。