在C#中初始化IEnumerable<string>

167

我有这个对象:

IEnumerable<string> m_oEnum = null;

我想初始化它。尝试过

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

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

9个回答

251

好的,除了先前提到的答案,你可能还在寻找其他内容

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

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

4
虽然年代有些久远,但我会避免第二个选项。你可能希望这可以与其他不兼容数组的IEnumerables进行交互。 - Joel Coehoorn
1
有时您需要将其转换为IEnumerable。然后像这样的语句就可以了:(IEnumerable<string>)new [] {"1", "2", "3"} - Carlo Bos

122

IEnumerable<T> 是一个接口。你需要使用具体类型(实现了 IEnumerable<T> 接口)来初始化它。 例如:

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

39

string[]实现了 IEnumerable

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

23

IEnumerable只是一个接口,因此无法直接实例化。

您需要创建一个具体类(例如List)。

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

你可以将它传递给任何期望一个 IEnumerable 的东西。


19
public static IEnumerable<string> GetData()
{
    yield return "1";
    yield return "2";
    yield return "3";
}

IEnumerable<string> m_oEnum = GetData();

13
虽然可能有些过头,但因为使用了yield,所以给一个赞(+1)。 - Adriano Carneiro
5
@AdrianCarneiro +1 为了这个押韵点赞 - 5argon

8

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

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

最简单的方法:new[] {...} - tobbenb3

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

感觉更像是一条评论而不是一个答案,正如所述。 - Mark Schultheiss

5
你可以创建一个静态方法来返回所需的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"};

0
这是一种使用新的global using在c# 10中实现的方法。
// this makes EnumerableHelpers static members accessible 
// from anywhere inside your project.
// you can keep this line in the same file as the helper class,
// or move it to your custom global using file.
global using static Utils.EnumerableHelpers;

namespace Utils;

public static class EnumerableHelpers
{
    /// <summary>
    /// Returns only non-null values from passed parameters as <see cref="IEnumerable{T}"/>.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="values"></param>
    /// <returns><see cref="IEnumerable{T}"/> of non-null values.</returns>
    public static IEnumerable<T> NewEnumerable<T>(params T[] values)
    {
        if (values == null || values.Length == 0) yield break;

        foreach (var item in values)
        {
            // I added this condition for my use case, remove it if you want.
            if (item != null) yield return item;
        }
    }
}

这是如何使用它的方法:
// Use Case 1
var numbers = NewEnumerable(1, 2, 3);

// Use Case 2
var strings = NewEnumerable<string>();
strings.Append("Hi!");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接