将单个项目作为 IEnumerable<T> 传递; [英] Passing a single item as IEnumerable&lt;T&gt;

查看:17
本文介绍了将单个项目作为 IEnumerable<T> 传递;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种通用的方法可以将 T 类型的单个项目传递给需要 IEnumerable 参数的方法?语言为C#,框架版本2.0.

Is there a common way to pass a single item of type T to a method which expects an IEnumerable<T> parameter? Language is C#, framework version 2.0.

目前我正在使用辅助方法(它是 .Net 2.0,所以我有一大堆类似于 LINQ 的转换/投影辅助方法),但这看起来很愚蠢:

Currently I am using a helper method (it's .Net 2.0, so I have a whole bunch of casting/projecting helper methods similar to LINQ), but this just seems silly:

public static class IEnumerableExt
{
    // usage: IEnumerableExt.FromSingleItem(someObject);
    public static IEnumerable<T> FromSingleItem<T>(T item)
    {
        yield return item; 
    }
}

其他方式当然是创建和填充 ListArray 并传递它而不是 IEnumerable.

Other way would of course be to create and populate a List<T> or an Array and pass it instead of IEnumerable<T>.

作为一个扩展方法,它可能被命名为:

As an extension method it might be named:

public static class IEnumerableExt
{
    // usage: someObject.SingleItemAsEnumerable();
    public static IEnumerable<T> SingleItemAsEnumerable<T>(this T item)
    {
        yield return item; 
    }
}

我在这里遗漏了什么吗?

Am I missing something here?

[Edit2] 我们发现 someObject.Yield()(正如@Peter 在下面的评论中建议的那样)是此扩展方法的最佳名称,主要是为了简洁,所以如果有人想抓住它,这里有 XML 注释:

We found someObject.Yield() (as @Peter suggested in the comments below) to be the best name for this extension method, mainly for brevity, so here it is along with the XML comment if anyone wants to grab it:

public static class IEnumerableExt
{
    /// <summary>
    /// Wraps this object instance into an IEnumerable&lt;T&gt;
    /// consisting of a single item.
    /// </summary>
    /// <typeparam name="T"> Type of the object. </typeparam>
    /// <param name="item"> The instance that will be wrapped. </param>
    /// <returns> An IEnumerable&lt;T&gt; consisting of a single item. </returns>
    public static IEnumerable<T> Yield<T>(this T item)
    {
        yield return item;
    }
}

推荐答案

你的辅助方法是最干净的方法,IMO.如果您传入一个列表或一个数组,那么一段不道德的代码可能会对其进行转换并更改内容,从而在某些情况下导致奇怪的行为.您可以使用只读集合,但这可能涉及更多的包装.我认为您的解决方案非常简洁.

Your helper method is the cleanest way to do it, IMO. If you pass in a list or an array, then an unscrupulous piece of code could cast it and change the contents, leading to odd behaviour in some situations. You could use a read-only collection, but that's likely to involve even more wrapping. I think your solution is as neat as it gets.

这篇关于将单个项目作为 IEnumerable<T> 传递;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆