正在初始化IEnumerable<;字符串>;在C#中
本文关键字:gt 字符串 lt 初始化 IEnumerable | 更新日期: 2023-09-27 18:00:58
我有这个对象:
IEnumerable<string> m_oEnum = null;
我想初始化它。尝试使用
IEnumerable<string> m_oEnum = new IEnumerable<string>() { "1", "2", "3"};
但上面写着"IEnumerable不包含添加字符串的方法。知道吗?谢谢
好的,在所述答案的基础上,您可能也在寻找
IEnumerable<string> m_oEnum = Enumerable.Empty<string>();
或
IEnumerable<string> m_oEnum = new string[]{};
IEnumerable<T>
是一个接口。您需要使用一个具体类型(实现IEnumerable<T>
(进行初始化。示例:
IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"};
由于string[]
实现了IEnumerable
IEnumerable<string> m_oEnum = new string[] {"1","2","3"}
IEnumerable
只是一个接口,因此不能直接实例化。
您需要创建一个具体的类(如List
(
IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3" };
然后,您可以将其传递给任何期望IEnumerable
的对象。
public static IEnumerable<string> GetData()
{
yield return "1";
yield return "2";
yield return "3";
}
IEnumerable<string> m_oEnum = GetData();
IEnumerable是一个接口,与其寻找如何创建接口实例,不如创建一个与接口匹配的实现:创建一个列表或数组。
IEnumerable<string> myStrings = new [] { "first item", "second item" };
IEnumerable<string> myStrings = new List<string> { "first item", "second item" };
不能实例化接口,必须提供IEnumerable的具体实现。
您可以创建一个静态方法,返回所需的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"};
以下是在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!");