获取单个或IEnumerable参数而不会过载

时间:2017-05-31 22:03:40

标签: c#

考虑以下两个重载函数。第一个只是将单个值包装到一个列表中并传递给一个接受多个值的那个。

我觉得不需要重载的单一功能。只有一个函数可以处理一个或一个可枚举的,是否有一个简单但不太蹩脚的方法?

    public static void Insert<T>(EntityType entityType, long entityId, string shortName, T value, string owner = null, OptionSearch optionSearch = OptionSearch.Name)
    {
        Insert(entityType, entityId, shortName, new List<T> {value}, owner, optionSearch);
    }

    public static void Insert<T>(EntityType entityType, long entityId, string shortName, IEnumerable<T> values, string owner = null, OptionSearch optionSearch = OptionSearch.Name)
    {
        // Do all the stuff and things using a list of values.
    }

通常情况下我不会关心重载,但是使用所有这些参数(并使它们成为一个输入对象不是一个选项)它只是让它看起来不需要。

PS:相关Passing a single item as IEnumerable<T>但是这只讨论了如何摆脱它而不是如何摆脱它的方法

2 个答案:

答案 0 :(得分:2)

除了评论中提出的建议外,没有办法避免过载,即: 您可以将values参数作为最后一个参数,将其更改为数组,然后使用params关键字:

public static void Insert<T>(... other parameters... , params T[] values)

然后,您将能够使用数组,单个T参数或多个逗号分隔的T参数调用该方法。但是,您无法使用任何IEnumerable<T>

我真的认为拥有过载是目前最好的方法。 要跟踪将IEnumerable<T> params参数纳入C#的建议,您可以使用以下链接:https://github.com/dotnet/csharplang/issues/179

答案 1 :(得分:1)

当然,只需使用一个以IEnumberable作为输入的方法,并要求用户将其单个参数转换为如下数组:

////Bool for example

Insert<bool>(... new bool[] { singleBool }, ...)

并将方法修改为:

public static void Insert<T>(EntityType entityType, long entityId, string shortName, IEnumerable<T> values, string owner = null, OptionSearch optionSearch = OptionSearch.Name)
{
    Insert(entityType, entityId, shortName, new List<T> {value}, owner, optionSearch);
}

虽然,我只是注意到,该方法引用自身...确保它做你想做的事。

相关问题