【问题标题】:Initializing IEnumerable<string> In C#在 C# 中初始化 IEnumerable<string>
【发布时间】:2011-07-04 14:54:38
【问题描述】:

我有这个对象:

IEnumerable<string> m_oEnum = null;

我想初始化它。尝试过

IEnumerable<string> m_oEnum = new IEnumerable<string>() { "1", "2", "3"};

但它说“IEnumerable 不包含添加字符串的方法。有什么想法吗?谢谢

【问题讨论】:

    标签: c# .net


    【解决方案1】:

    好的,添加到您可能在寻找的答案

    IEnumerable<string> m_oEnum = Enumerable.Empty<string>();
    

    IEnumerable<string> m_oEnum = new string[]{};
    

    【讨论】:

    • 现在旧了,但我会避免使用第二种选择。您可能希望它与其他与数组不兼容的 IEnumerable 交互。
    • 有时您需要将其转换为 IEnumerable。然后这样的声明就可以了:(IEnumerable&lt;string&gt;)new [] {"1", "2", "3"}
    【解决方案2】:

    IEnumerable&lt;T&gt; 是一个接口。您需要使用具体类型(实现IEnumerable&lt;T&gt;)启动。示例:

    IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"};
    

    【讨论】:

      【解决方案3】:

      由于string[] 实现了 IEnumerable

      IEnumerable<string> m_oEnum = new string[] {"1","2","3"}
      

      【讨论】:

        【解决方案4】:

        IEnumerable只是一个接口,不能直接实例化。

        你需要创建一个具体的类(比如List

        IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3" };
        

        然后,您可以将其传递给任何期望 IEnumerable 的对象。

        【讨论】:

          【解决方案5】:
          public static IEnumerable<string> GetData()
          {
              yield return "1";
              yield return "2";
              yield return "3";
          }
          
          IEnumerable<string> m_oEnum = GetData();
          

          【讨论】:

          • 虽然有点矫枉过正,使用yield +1
          • @AdrianCarneiro +1 押韵
          【解决方案6】:

          您不能实例化接口 - 您必须提供 IEnumerable 的具体实现。

          【讨论】:

            【解决方案7】:

            您可以创建一个静态方法,该方法将返回所需的 IEnumerable,如下所示:

            public static IEnumerable<T> CreateEnumerable<T>(params T[] values) =>
                values;
            //And then use it
            IEnumerable<string> myStrings = CreateEnumerable("first item", "second item");//etc..
            

            或者只是做:

            IEnumerable<string> myStrings = new []{ "first item", "second item"};
            

            【讨论】:

              【解决方案8】:

              IEnumerable是一个接口,而不是寻找如何创建一个接口实例,创建一个与该接口匹配的实现:创建一个列表或一个数组。

              IEnumerable<string> myStrings = new [] { "first item", "second item" };
              IEnumerable<string> myStrings = new List<string> { "first item", "second item" };
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2017-12-14
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多