为什么PARAMS这样的表现? [英] Why does params behave like this?

查看:102
本文介绍了为什么PARAMS这样的表现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

输出


  

1


  
  

2


  
  


  
  

2


code

 类节目
{
    静态无效的主要(字串[] args)
    {
        字符串s = NULL;
        PrintLength(多个);
        PrintLength(S,S);
        PrintLength(NULL);
        PrintLength(NULL,NULL);
        Console.ReadKey();
    }    私有静态无效PrintLength(PARAMS的String []项)
    {
        Console.WriteLine(项==空空:items.Length.ToString());
    }
}


解决方案

这是一个相当常见的问题。有关详细信息,请参阅该规范第7.4.1和7.4.3.1。

简单:用参数数组的方法适用于任何的范式或其展开的形式。也就是说,你可以说

  PrintLength(新的String [] {你好}); //范式
PrintLength(你好); //扩展的形式,由编译器转换成正常形态。

在发出了呼叫,在适用的这两种形式的,编译器总是选择在扩展形式的正常形态。

假设我们每个人都适用的时间选择的扩展形式。假设你有

 无效M(params对象[]×){}

如何实际上传递一个空数组,这件事情,如果我们总是选择的扩展形式?这将是不可能的!

假设你说

  M(新的对象[] {你好});

和我们总是选择的扩展形式。你会这样吗?那么,对象的数组是一个对象,因此这将选择的扩展形式 - 它将使的其他的阵列,组成阵列的包裹这件事情,并传递

扩展形式在正常形式的选择会导致疯狂的结果。在展开形式总是选择正常形态是应该做的更明智的事情。

Output

1

2

null

2

Code

class Program
{        
    static void Main(String[] args)
    {
        String s = null;
        PrintLength(s);
        PrintLength(s, s);
        PrintLength(null);
        PrintLength(null, null);    
        Console.ReadKey();
    }

    private static void PrintLength(params String[] items)
    {
        Console.WriteLine(items == null ? "null" : items.Length.ToString());
    }    
}

解决方案

This is a fairly frequently asked question. For details, see section 7.4.1 and 7.4.3.1 of the specification.

Briefly: a method with a params array is applicable in either its "normal form" or its "expanded form". That is, you can say

PrintLength(new string[] {"hello"}); // normal form
PrintLength("hello"); // expanded form, translated into normal form by compiler.

When given a call that is applicable in both forms, the compiler always chooses the normal form over the expanded form.

Suppose we chose the expanded form every time both were applicable. Suppose you had

void M(params object[] x) {}

How would you actually pass a null array to this thing if we always chose the expanded form? That would be impossible!

Suppose you said

M(new object[] { "hello" });

and we always chose the expanded form. What would this do? Well, an array of objects is an object, so this would choose the expanded form -- it would make another array, wrap this thing up in the array, and pass that!

The choice of expanded form over normal form leads to crazy results. Always choosing the normal form over the expanded form is the more sensible thing to do.

这篇关于为什么PARAMS这样的表现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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