关键字“参数"到底如何工作? [英] How exactly keyword 'params' work?
本文介绍了关键字“参数"到底如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码示例打印:
T
T[]
T[]
前两行符合预期,为什么编译器选择param数组作为常规数组?
While first two lines are as expected, why compiler selected param array for a regular array?
public class A
{
public void Print<T>(T t)
{
Console.WriteLine("T");
}
public void Print<T>(params T[] t)
{
Console.WriteLine("T[]");
}
}
class Program
{
static void Main(string[] args)
{
A a = new A();
a.Print("string");
a.Print("string","string");
a.Print(new string[] {"a","b"});
}
}
推荐答案
内幕
a.Print("string","string");
仅仅是...的语法糖
a.Print(new string[]{"string","string"});
就像我说的那样, params
关键字仅自动为您创建数组,您告诉编译器:直接接受 T
数组或使用X输入参数来构造该数组.
Like I said, the params
keyword only automagically creates the array for you, you tell the compiler: either accept an array of T
directly or use the X input params to construct that array.
这篇关于关键字“参数"到底如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文