本文介绍了C#泛型和类型检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用 IList< T> 作为参数的方法.我需要检查该 T 对象的类型是什么,并基于它进行一些操作.我试图使用 T 值,但是编译器不允许使用它.我的解决方案如下:

I have a method that uses an IList<T> as a parameter. I need to check what the type of that T object is and do something based on it. I was trying to use the T value, but the compiler does not not allow it. My solution is the following:

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 语句?

There has to be a better way to do this. Is there some way I can check the type of T that is passed in and then use a switch statement?

推荐答案

您可以使用重载:

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

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

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

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

Or you could inspect the type of the generic parameter:

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

这篇关于C#泛型和类型检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 03:42