本文介绍了C#可变长度args,哪个更好,为什么:__ arglist,params数组或Dictionary< T,K&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近阅读了以下溢出帖子: C#的隐藏功能

I recently read the following overflow post:Hidden Features of C#

指出的功能之一是arglist.为什么要选择此方法或替代方法作为对方法使用可变长度参数列表的一种方法?另外,请注意,除非必要,否则我可能不会在代码中使用这种构造.这更多是语义问题,而不是使用可变长度参数是否实际还是谨慎.那么,有谁知道哪个更好,为什么呢?

One of the features pointed out was the arglist. Why would one choose this or the alternatives as a means of using a variable length argument list to a method? Also, note that I would probably not use this kind of construct in my code unless a corner case warranted doing so. This is more of a question of semantics than whether it is even practical or prudent to even use variable length arguments. So does anyone know which is better and why?

 [Test]
 public void CanHandleVariableLengthArgs()
 {
     TakeVariableLengthArgs(__arglist(new StringBuilder(), 12));

     object[] arr = { new StringBuilder() };
     TakeVariableLengthArgs2(arr);

     TakeVariableLengthArgs3(
         new Dictionary<string, object> 
         { { "key", new StringBuilder() } });
 }

 public void TakeVariableLengthArgs(__arglist)
 {
      var args = new ArgIterator(__arglist);

      var a = (StringBuilder)TypedReference.ToObject(args.GetNextArg());
      a.Append(1);
 }

 public void TakeVariableLengthArgs2(params object[] args)
 {
      var a = (StringBuilder)args[0];
      a.Append(1);
 }

 public void TakeVariableLengthArgs3(Dictionary<string, object> args)
 {
      var a = (StringBuilder)args["StringBuilder"];
      a.Append(1);
 }

推荐答案

我当然不会使用__arglist,因为它没有文档说明,在任何情况下都没人知道它的含义.

I would certainly never use __arglist, since it's undocumented and nobody knows what it means in any case.

我也将尽可能地避免使用变长参数列表,而是重新设计以了解什么是真正的变量,并以与平台无关的方式对这种可变性进行建模.

I'd also avoid variable-length argument lists for as long as possible, and instead rework my design to understand what is truly variable, and to model that variability in a less platform-dependant manner.

这篇关于C#可变长度args,哪个更好,为什么:__ arglist,params数组或Dictionary&lt; T,K&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 00:09