确定List的类型

本文关键字:类型 List 确定 | 更新日期: 2023-09-27 17:49:43

在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...
}

确定List的类型

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

:

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

可以使用

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

在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。

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