带可选参数的方法

时间:2015-04-28 15:11:22

标签: c# linq

我有一个方法,它有四个参数,我用来过滤我的数据,有时4个参数被填充,有时只有三个或两个或一个被填充,所以我一直在寻找一种方法来只采取必要的参数值。例如,如果用户只输入一个参数,如startDate,我想恢复该日期的所有数据,而不将其他参数作为 static void Main(string[] args) { string firstname = ""; string lastName = ""; string variablewithdata = "SQL injection - Wikipedia, -the free encyclopedia - Mozilla Firefox"; // variablewithdata.LastIndexOf('-') = returns Integer corresponding to the last position of that character. //I suggest you validate if variablewithdata.LastIndexOf('-') is equal to -1 or not because if it don't found your character it returns -1 so if the value isn't -1 you can substring firstname = variablewithdata.Substring(0, (variablewithdata.LastIndexOf('-') - 1)); lastName = variablewithdata.Substring(variablewithdata.LastIndexOf('-') + 1); Console.WriteLine("FirstColumn: {0} \nLastColumn:{1}",firstname,lastName); Console.ReadLine(); } ,但不应考虑它们,我的方法搜索具有正确的StartDate和其他参数AccessToken.getCurrentAccessToken().getToken();我不想这样做

null

4 个答案:

答案 0 :(得分:3)

选项1:过载。 创建4个方法,每个方法都有一个不同的签名,用于调用" main" -method,例如具有完整参数的方法。调用伴随着一些默认参数。

internal static List<Inconsistence> FilterList(DateTime? StartDate, DateTime? EnDate, decimal? State)
{
    return FilterList(StartDate, EnDate, State, null); // Call overloaded method with Type = null
}

internal static List<Inconsistence> FilterList(DateTime? StartDate, DateTime? EnDate, decimal? State, decimal? Type)

选项2:默认值 您可以为method-parameter指定一个默认值。只有最后一个参数可以具有默认值。看起来像这样

internal static List<Inconsistence> FilterList(DateTime? StartDate, DateTime? EnDate, decimal? State, decimal? Type = null)

这个Type - 参数是可选的。如果未在呼叫中指定,则将具有指定的默认值。在这种情况下,它是null

答案 1 :(得分:0)

您可以将参数设为可选:MSDN

internal static List<Inconsistence> FilterList(DateTime? StartDate, DateTime? EnDate = null, decimal? State = null, decimal? Type = null)

答案 2 :(得分:0)

我认为你可以像这样编写你的where子句:

.Where( g =>
  (State.HasValue.Equals(false) || g => g.r.uir.InconsistencyStateId == State) && 
  (Type.HasValue.Equals(false) || g.r.uir.InconsistencyTypeId == Type) &&
  (StartDate.HasValue.Equals(false) || g.r.uir.InsDate >= StartDate) &&
  (EnDate.HasValue.Equals(false) || EnDate >= g.r.uir.InsDate)
)

我没有对它进行过测试,但它应该有效。

答案 3 :(得分:0)

params可以为您做到这一点,但您需要将值向下转换为object

将函数定义为

internal static List<Inconsistence> FilterList(params object[] list)
{
   //check the size of `list` object and cast the values
   (DateTime)list[0]
   (double)list[1]
}

,电话会是

FilterList(DateTime.Now);
FilterList(DateTime.Now, 1.0);
相关问题