.net 在< string>C#中初始化IEnumerable

zfycwa2u  于 2023-06-25  发布在  .NET
关注(0)|答案(9)|浏览(125)

我有这个对象:

IEnumerable<string> m_oEnum = null;

我想初始化它。试过

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

但它说“IEnumerable不包含添加字符串的方法。知道吗?谢谢

sczxawaw

sczxawaw1#

好吧,加上你所陈述的答案,你可能也在寻找

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

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

xghobddn2#

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

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

flmtquvp3#

由于string[]实现了IEnumerable

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

2wnc66cl4#

IEnumerable只是一个接口,所以不能直接示例化。
您需要创建一个具体的类(如List

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

然后你可以把它传递给任何期望IEnumerable的东西。

cbwuti44

cbwuti445#

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

IEnumerable<string> m_oEnum = GetData();
mwngjboj

mwngjboj6#

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

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

eit6fx6z7#

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

smdncfj3

smdncfj38#

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

nbysray59#

这里有一种方法,通过在c# 10中使用新的global using来实现。

// 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!");

相关问题