将数组传递给采用params object []或IEnumerable< T>的函数. [英] Passing array to function that takes either params object[] or IEnumerable<T>

查看:72
本文介绍了将数组传递给采用params object []或IEnumerable< T>的函数.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将自定义对象的数组传递给像String.Join这样的函数,该函数具有以下签名:

I want to pass an array of custom objects to a function like String.Join which has the following signatures:

  • public static string Join(string separator, params Object[] values)
  • public static string Join(string separator, IEnumerable<T> values)
  • public static string Join(string separator, params Object[] values)
  • public static string Join(string separator, IEnumerable<T> values)

如果我这样调用函数:

var arr = new MyClass[]{ new MyClass(), new MyClass() };
string text = string.Join("\n", arr);

我收到一个编译器错误:

I get a compiler error:

以下方法或属性之间的调用不明确:'string.Join(string,params object [])'和'string.Join(string,System.Collections.Generic.IEnumerable)'

The call is ambiguous between the following methods or properties: 'string.Join(string, params object[])' and 'string.Join(string, System.Collections.Generic.IEnumerable)'

我可以使用IEnumerable<T>函数解决歧义:

I can resolve the ambiguity by using the IEnumerable<T> function:

var arr = new MyClass[]{ new MyClass(), new MyClass() };
string text = string.Join<MyClass>("\n", arr);

但是我可以调用params object[]函数吗?

But can I call the params object[] function?

我正在使用C#4.0,如果有什么区别.

I am using C# 4.0, if that makes any difference.

推荐答案

如果将object[]作为第二个参数传递,则编译器应选择object[]重载,因为它完全匹配.如果您使用其他类型的数组(在本例中为MyClass[]),只需将该数组转换为object[]:

If you pass an object[] as the second parameter, the compiler should choose the object[] overload since it exactly matches. In the case where you have a differently-typed array (MyClass[] in this case) just cast the array to object[]:

string.Join("\n", (object[])arr);

您实际上并没有在运行时更改任何对象的类型或执行任何转换,只是向编译器提供了有关使用哪种重载的提示.

You are not actually changing the types of any objects or performing any conversion at runtime, you're only giving the compiler a hint regarding which overload to use.

关于您对性能的评论,如果性能至关重要,请不要忘记对这两个选项进行基准测试.不要以为一个比另一个要快. (并且始终对整个应用程序进行概要分析-任何瓶颈都可能在其他地方.)

And regarding your comment about performance, don't forget to benchmark both options if performance is that critical. Don't assume one is faster than the other. (And always profile your entire application -- it's likely that any bottlenecks are going to be elsewhere.)

这篇关于将数组传递给采用params object []或IEnumerable&lt; T&gt;的函数.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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