简体   繁体   English

如何将数量不确定的参数传递给基本构造函数?

[英]How to pass undetermined number of arguments to base constructor?

If this is possible at all, what should replace %PARAMS% ? 如果完全有可能,应怎么替换%PARAMS%

class ParentClass
{
    public BaseClass( params int[] intList )
    { (...) }
}

class ChildClass : BaseClass
{
    public ChildClass( params int[] intList ) : base( %PARAMS% )
    { (...) }
}

PS.: Sorry if its a newbie question, I just started writing C#. PS .:很抱歉,如果这是一个新手问题,我才刚开始编写C#。

Try just 尝试一下

public ChildClass( params int[] intList ) : base( intList )

See 10.5.1.4 Parameter arrays (emphasis mine): 参见10.5.1.4参数数组 (强调我的):

A parameter array permits arguments to be specified in one of two ways in a method invocation: 参数数组允许在方法调用中以两种方式之一指定参数:

  • The argument given for a parameter array can be a single expression of a type that is implicitly convertible (Section 6.1) to the parameter array type . 为参数数组提供的参数可以是类型的单个表达式,该类型表达式可以隐式转换为参数数组type(第6.1节) In this case, the parameter array acts precisely like a value parameter. 在这种情况下,参数数组的作用恰好类似于值参数。
  • Alternatively, the invocation can specify zero or more arguments for the parameter array, where each argument is an expression of a type that is implicitly convertible (Section 6.1) to the element type of the parameter array. 或者,调用可以为参数数组指定零个或多个参数,其中每个参数都是一种类型的表达式,该类型可以隐式转换为参数数组的元素类型(第6.1节)。 In this case, the invocation creates an instance of the parameter array type with a length corresponding to the number of arguments, initializes the elements of the array instance with the given argument values, and uses the newly created array instance as the actual argument. 在这种情况下,调用将创建一个参数数组类型的实例,该实例的长度与参数的数量相对应,并使用给定的参数值初始化该数组实例的元素,并将新创建的数组实例用作实际参数。

So if there is a function: 因此,如果有一个功能:

 void Function(params int[] list) {  }

it can be called in different ways: 可以用不同的方式调用它:

Function(0, 1, 2, 3);
Function(new int[] { 0, 1, 2, 3 });
var a = new int[] { 0, 1, 2, 3 };
Function(a);
ChildClass c = new ChildClass(1, 2, 3);

Does this correspond to your needs? 这符合您的需求吗?

class ParentClass
{
    public BaseClass( params int[] ints )
    {  }
}

class ChildClass : BaseClass
{
    public ChildClass( params int[] ints ) : base( ints )
    {  }
}

or this: 或这个:

class ParentClass
{
    public BaseClass( IEnumerable<int> ints )
    {  }
}

class ChildClass : BaseClass
{
    public ChildClass( IEnumerable<int> ints ) : base( ints )
    {  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM