如何确定给定对象是通用列表<t>还是列表列表<t>?

时间:2015-11-20 09:50:33

标签: c# asp.net .net generics reflection

List<List<HeaderTypeEnq<dynamic>>> IDEnq = new List<List<HeaderTypeEnq<dynamic>>>();
List<HeaderTypeEnq<dynamic>> IDListEnq = new List<HeaderTypeEnq<dynamic>>();

for (int i = 0; i < enq.Id.Count; i++)
{
    IDListEnq.Add(new HeaderTypeEnq<dynamic>() { FieldTag = "ID", FieldName = "Segment Tag", Value = enq.Id[i].SegmentTag, Mandatory = "Y", CharacterType = "A", MaxLength = 03 });
    IDListEnq.Add(new HeaderTypeEnq<dynamic>() { FieldTag = "01", FieldName = "ID Type", Value = enq.Id[i].IDType, Mandatory = "Y", CharacterType = "N", MaxLength = 02 });
    IDListEnq.Add(new HeaderTypeEnq<dynamic>() { FieldTag = "02", FieldName = "ID Number", Value = enq.Id[i].IDNumber, Mandatory = "N", CharacterType = "P", MaxLength = 30 });
    IDEnq.Add(IDListEnq);
}
ValidateValue<List<HeaderTypeEnq<dynamic>>>(IDEnq, concaDel);


private string ValidateValue<T>(object EnqTagList, ValidationDelegate del)
{
    //errorstr = "";

    Type typeParameterType = typeof(T);
    if (typeof(T) == typeof(List<HeaderTypeEnq<dynamic>>))
    {
        //code
    }

根据我的理解if (typeof(T) == typeof(List<HeaderTypeEnq<dynamic>>))应该为IDEnq(列表清单)返回false,但它返回true!

2 个答案:

答案 0 :(得分:1)

为了检查类型t是否是列表列表,您可以执行以下操作:

if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>))
{
    Type elementType = t.GetGenericArguments()[0];

    if (elementType.IsGenericType && elementType.GetGenericTypeDefinition() == typeof(List<>))
        Console.WriteLine("t is a list of lists");
    else
        Console.WriteLine("t is just a list");
}
else
    Console.WriteLine("t is not a list");

答案 1 :(得分:0)

  

根据我的理解if(typeof(T)== typeof(List&gt;))应该为IDEnq(列表列表)返回false,但它返回true!

您正在调用这样的通用类型

 ValidateValue<List<HeaderTypeEnq<dynamic>>>(IDEnq, concaDel);

通用类型是List<HeaderTypeEnq<dynamic>>。这与IDEnq object无关。因此,当你调用这样的方法时,T恰好是List<HeaderTypeEnq<dynamic>>的类型,条件变为真。

您可以像这样制作通用方法。 现在EnqTagList是T.您需要获取其元素的类型。

private string ValidateValue<T>(T EnqTagList, ValidationDelegate del) 
{
    if (EnqTagList.GetType().GetGenericArguments()[0] == typeof(List<HeaderTypeEnq<dynamic>>))
    {
     //code
    }
}