问题
I have one function having two fixed arguments. But next arguments are not fixed, there can be two or three or four of them.
It's a runtime arguments so how can I define that function?
My code looks like:
public ObservableCollection<ERCErrors> ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, dynamic arguments comming it should be 2 or 3)
{
return null;
}
回答1:
1) params (C# Reference)
public ObservableCollection<ERCErrors>ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, params object[] args)
{
//...
}
2) Named and Optional Arguments (C# Programming Guide)
public ObservableCollection<ERCErrors> ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, object arg1 = null, int arg2 = int.MinValue)
{
//...
}
3) And maybe simple method overloading would still suit better, separating method logic to different methods? Under this link you can also find another description of named and optional parameters
回答2:
One approach is to have overloaded methods
public ObservableCollection<ERCErrors> ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, int param1)
{
//do some thing with param1
}
public ObservableCollection<ERCErrors> ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, int param1,int param2)
{
//do some thing with param1 and param3
}
public ObservableCollection<ERCErrors> ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, int param1, int param2, int param3)
{
//do some thing with param1, param2 and param3
}
then all these would be valid
var err = ErrorCollectionWithValue("text", 10, 1);
var err = ErrorCollectionWithValue("text", 10, 1,2);
var err = ErrorCollectionWithValue("text", 10, 1,2,3);
Another approach is to use optional parameters. With this you need only one method as opposed to the 3 in the first approach.
public ObservableCollection<ERCErrors> ErrorCollectionWithValue
(string ErrorDode, int MulCopyNo, int param1 = 0, int param2 = 0, optional int param3 = 0)
{
}
these are still valid
var err = ErrorCollectionWithValue("text", 10, 1); //defaults param2 and param3 to 0
var err = ErrorCollectionWithValue("text", 10, 1,2); //defaults param3 to 0
var err = ErrorCollectionWithValue("text", 10, 1,2,3);
To skip any of the optional parameters, you need to use named parameters and this which is only supported in C# 4.0 and above
var err = ErrorCollectionWithValue("text", param3: 5); //skipping param1 and param2
In the other two approaches, you can't skip the order of the parameters.
回答3:
You could go with params, if the number of argument may vary:
public ObservableCollection<ERCErrors> ErrorCollectionWithValue(string errorCode, int num, params object[] args)
{
foreach(object obj in args)
{
//process args.
}
}
来源:https://stackoverflow.com/questions/12577730/how-to-pass-optional-arguments