我有一个使用 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/