我有这个对象:
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" };
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"};
// 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!");
(IEnumerable<string>)new [] {"1", "2", "3"}
- Carlo Bos