如何在方法中传递多个值作为参数?

时间:2016-12-12 18:01:24

标签: c# generics

我有一个方法,我想发送几个参数或一个或没有

public void CalcBreakpoint(int tolerance, [I want to send several parameters or one or none])
{
//my code
}

例如我想将其称为CalcBreakpoint(200,“string value1”,“string value 2”,“String Value 3”)

在其他场合我会称之为 CalcBreakpoint(500,object1,object2)

我想避免重载,因为90%的代码是相同的。

如何在方法中传递多个值作为参数?比如

public void CalcBreakpoint(int tolerance,[ONE_PARAMETER])

2 个答案:

答案 0 :(得分:4)

如果它们永远是字符串,你可以这样做:

public void void CalcBreakpoint(int tolerance, params string[] args)
{
    //my code
}

如果它们是您设置的参数:

public void params void CalcBreakpoint(int tolerance, string arg1 = null, int? arg2 = null, object arg3 = null, decimal? arg4 = null)
{
    //my code
}

第二个让你能够像这样调用它:

CalcBreakpoint(34, arg3: "asdf");

答案 1 :(得分:0)

除了maksymiuk的优秀建议外,我还想指出您还可以做以下其中一项:

// If you're using "mixed types"
public void CalcBreakpoint(int tolerance, params object[] args)
{
   //...
}

// The use of dynamic here is controversial but it can accomplish something similar to the above code sample
public void void CalcBreakpoint(int tolerance, params dynamic[] args)
{
    //....
}

// If all of the arguments are of the same type but you don't know "in advance"
// what that type will be, you can use generics here
public void CalcBreakpoint<T>(int tolerance, params T[] args)
{
    //my code
}