Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何从数据源获取对象的类型?_C#_.net_Types - Fatal编程技术网

C# 如何从数据源获取对象的类型?

C# 如何从数据源获取对象的类型?,c#,.net,types,C#,.net,Types,我在一个中继器中,我想检查它的重复对象是哪种类型的onitemdata绑定的,但这样做: public void RepeaterListato_OnItemDataBound(Object Sender, RepeaterItemEventArgs e) { Response.Write(repeaterListato.DataSource.GetType()); } 它返回整个集合的类型: System.Collections.Generic.List`1[BrLayer.Pagi

我在一个
中继器中
,我想检查它的重复对象是哪种类型的
onitemdata绑定的
,但这样做:

public void RepeaterListato_OnItemDataBound(Object Sender, RepeaterItemEventArgs e)
{
    Response.Write(repeaterListato.DataSource.GetType());
}
它返回整个集合的类型:

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

BrLayer.Pagina
。有办法吗?

绝对有可能!下面是一个工作示例:

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();
    }
}
类程序
{
静态列表MyGenericList=新列表();
静态void Main(字符串[]参数)
{
WriteLine($“我的列表类的类型是:{MyGenericList.GetType()},它的第一个泛型参数是:{MyGenericList.GetType().GetGenericArguments()[0]}”);
Console.ReadLine();
}
}

注意调用
Type.GetType().GetGenericArguments()
,这就是神奇之处。它将返回原始类型的所有泛型参数的数组。

事件处理程序有一个参数
RepeaterItemEventArgs e

你想要:

e.Item.DataItem.GetType()
请注意,如果
e.Item.DataItem
页眉
页脚
分隔符
页面
,则
e.Item.DataItem
将为空;因此,如果您的中继器可能有任何这些元素,您应该检查null或检查
ItemType


请注意,将为数据源中的每个项调用OnItemDataBound,并且在一般情况下,不能保证所有项都具有相同的类型。

可能重复@derape,中继器不一定绑定到泛型集合,因此您建议的重复是不适当的。为什么要进行向下投票?特别是没有一个有用的评论来解释如何改进这个问题。我投了反对票,因为可能会被愚弄。正如我们在您的问题中所看到的,集合类型为
List
。列表实例所在的位置无关紧要……输入:its
e.Item.DataItem.GetType()
谢谢