C# ジェネリックと型チェック 質問する

C# ジェネリックと型チェック 質問する

をパラメータとして使用するメソッドがあります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?

ベストアンサー1

オーバーロードを使用することもできます:

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)){...}

おすすめ記事