Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

c# - Passing array to function that takes either params object[] or IEnumerable<T>

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)

If I call the function like this:

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

I get a compiler error:

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

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

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

But can I call the params object[] function?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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("
", (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.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...