确定列表的类型?

时间:2012-12-26 08:08:40

标签: c# list

在c#中,我们可以确定List在执行其他操作之前所持有的类型吗?例如:

List<int> listing = new List<int>();

if(listing is int)
{
    // if List use <int> type, do this...
}
else if(listing is string)
{
    // if List use <string> type, do this...
}

3 个答案:

答案 0 :(得分:4)

您可以使用Type.GetGenericArguments()方法。

像:

Type[] types = list.GetType().GetGenericArguments();
if (types.Length == 1 && types[0] == typeof(int))
{
    ...
}

答案 1 :(得分:3)

您可以使用

if(listing is List<int>) ...

答案 2 :(得分:1)

当使用面向对象语言编写为c#时,我们通常更喜欢使用多态而不是在运行时类型上使用条件。下次尝试这样的事情,看看你是否喜欢它!

interface IMyDoer
{
    void DoThis();
}

class MyIntDoer: IMyDoer
{
    private readonly List<int> _list;
    public MyIntClass(List<int> list) { _list = list; } 
    public void DoThis() { // Do this... }
}
class MyStringDoer: IMyDoer
{
    private readonly List<string> _list;
    public MyIntClass(List<string> list) { _list = list; } 
    public void DoThis() { // Do this... }
}

这样打电话:

doer.DoThis(); // Will automatically call the right method
//depending on the runtime type of 'doer'!

代码变得更短更清晰,你不必拥有if语句的djungle。

这种安排代码(或分解)的方法,您可以自由地更改代码的内部结构而不会破坏它。如果你使用条件,你会发现代码很容易破坏,例如修复一个不相关的问题。这是代码的一个非常有价值的属性。希望你觉得这很有帮助!