【问题标题】:Determine type of a List? [duplicate]确定列表的类型? [复制]
【发布时间】:2012-12-26 08:08:39
【问题描述】:

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

【问题讨论】:

    标签: c# list


    【解决方案1】:

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

    喜欢:

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

    【讨论】:

      【解决方案2】:

      你可以使用

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

      【讨论】:

      • +1 虽然这两个答案都为所提出的问题提供了解决方案,但我相信这是解决这个特定问题的更好解决方案。尽管Type.GetGenericArguments() 方法有非常有效的用途,但这种用法只是引入了不必要的反射级别(然后仍然必须使用 typeof 来检查泛型类型参数),因为已知变量是 List。这个答案提供了一个更有效的解决方案,需要更少的代码。
      【解决方案3】:

      当使用 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 语句了。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-12-19
        • 2014-09-16
        • 1970-01-01
        • 2011-05-24
        • 1970-01-01
        • 2018-02-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多