2017-08-09 31 views
-2

我是Repeater内,我想看看哪种对象的重复OnItemDataBound,但是这样做:如何从DataSource获取对象的类型?

public void RepeaterListato_OnItemDataBound(Object Sender, RepeaterItemEventArgs e) 
{ 
    Response.Write(repeaterListato.DataSource.GetType()); 
} 

它返回整个集合的类型:

System.Collections.Generic.List`1[BrLayer.Pagina] 

BrLayer.Pagina。有没有办法?

+1

[如何从泛型类或方法的成员获取T的类型?](https://stackoverflow.com/questions/557340/how-to-get-the-type-of- t-from-a-generic-class-or-method) – derape

+1

@derape,Repeater不一定绑定到泛型集合,所以你的提示是不合适的。 – Joe

+1

为什么downvotes?特别是没有有用的评论来解释如何改善问题。 – Joe

回答

1

OnItemDataBound事件处理函数的参数为​​RepeaterItemEventArgs e

你想:

e.Item.DataItem.GetType() 

注意e.Item.DataItem将是无效的,如果e.Item.ItemTypeHeaderFooterSeparatorPager;所以你应该检查空值或检查ItemType如果你的中继器可能有任何这些元素。

请注意,OnItemDataBound将针对DataSource中的每个项目调用,并且在一般情况下,不能保证所有项目都具有相同的Type。

+0

typo:它的'e.Item.DataItem.GetType()'谢谢 – markzzz

+0

@markzzz - true,已更正。 – Joe

1

绝对有可能!这里有一个工作示例:

class Program 
{ 
    static List<string> MyGenericList = new List<string>(); 

    static void Main(string[] args) 
    { 
     Console.WriteLine($"My list class's type is: {MyGenericList.GetType()}, and its first generic argument is: {MyGenericList.GetType().GetGenericArguments()[0]}"); 
     Console.ReadLine(); 
    } 
} 

通知调用Type.GetType().GetGenericArguments(),这就是神奇的发生。它会返回一个包含原始类型的所有通用参数的数组。