C#可变长度ARGS,这是更好的,为什么:__arglist,参数数组或字典< T,K&GT ;? [英] C# variable length args, which is better and why: __arglist, params array or Dictionary<T,K>?

查看:465
本文介绍了C#可变长度ARGS,这是更好的,为什么:__arglist,参数数组或字典< T,K&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近看了以下的溢出职位:C#的 <
隐藏的功能/ p>

的特点之一,指出是arglist中。为什么人会选择这种或替代品使用可变长度的参数列表的方法的手段?另请注意,除非一个角落的情况下保证这样做我可能不会使用这种构造的在我的代码。这是更比语义无论是实际的,甚至还是谨慎甚至使用可变长度参数的问题。因此,没有人知道哪个好,为什么?



  [测试] 
公共无效CanHandleVariableLengthArgs()
{
TakeVariableLengthArgs(__ arglist中(新的StringBuilder(),12));

对象[] =改编新{的StringBuilder()};
TakeVariableLengthArgs2(ARR);

TakeVariableLengthArgs3(
新字典<字符串对象>
{{钥匙,新的StringBuilder()}});
}

公共无效TakeVariableLengthArgs(__ arglist中)
{
变参=新ArgIterator(__ arglist中);

VAR一个=(StringBuilder)对TypedReference.ToObject(args.GetNextArg());
a.Append(1);
}

公共无效TakeVariableLengthArgs2(params对象[]参数)
{
VAR一个=(StringBuilder的)ARGS [0];
a.Append(1);
}

公共无效TakeVariableLengthArgs3(词典<字符串对象>参数)
{
VAR一个=(StringBuilder的)ARGS [的StringBuilder];
a.Append(1);
}


解决方案

我肯定不会使用__arglist ,因为它是无证,没有人知道这意味着什么,无论如何。



我也避免可变长度参数列表,只要有可能,而是返工我的设计要了解什么是真正的变量,并在一个不太依赖于平台的方式变化的模型。


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

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);
 }

解决方案

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,参数数组或字典&LT; T,K&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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