可变的参数数目不拳击的价值类型?拳击、数目、参数、类型

2023-09-03 16:05:06 作者:@考神

public void DoSomething(params object[] args)
{
    // ...
}

与上面的签名问题是,每个值类型将被传递给该方法将被隐式装箱,这是严重的性能问题对我来说。

The problem with the above signature is that every value-type that will be passed to that method will be boxed implicitly, and this is serious performance issue for me.

有没有办法declear接受可变数量的参数没有拳击的价值类型的方法?

Is there a way to declear a method that accepts variable number of arguments without boxing the value-types?

感谢。

推荐答案

您可以使用泛型:

public void DoSomething<T>(params T[] args)
{
}

然而,这将只允许指定一个单一类型的ValueType的。如果你需要混合或匹配值的类型,你就必须让拳击发生,因为你现在所做的,或不同数量的参数提供具体的重载。

However, this will only allow a single type of ValueType to be specified. If you need to mix or match value types, you'll have to allow boxing to occur, as you're doing now, or provide specific overloads for different numbers of parameters.

编辑:如果你需要不止一种类型的参数,你可以使用重载做到这一点,在一定程度上

If you need more than one type of parameter, you can use overloads to accomplish this, to some degree.

public void DoSomething<T,U>(T arg1, params U[] args) {}
public void DoSomething<T,U>(T arg1, T arg2, params U[] args) {}

不幸的是,这需要多个重载存在你的类型。

Unfortunately, this requires multiple overloads to exist for your types.

另外,你可以传递数组直接:

Alternatively, you could pass in arrays directly:

public void DoSomething<T,U>(T[] args1, U[] args2) {}

您失去了不错的编译器的语法,但你可以拥有任意数量通过这两个参数。

You lose the nice compiler syntax, but then you can have any number of both parameters passed.