动态改变在C#中的if语句的条件 [英] Dynamically changing conditions of an if statement in C#

查看:1047
本文介绍了动态改变在C#中的if语句的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的算法,其目的是创建日期的集合在其上有一定的事件发生(使我可以大胆它们放在MonthCalendar控件,或以其他方式显示它们)。

I'm working on an algorithm whose purpose is to create a collection of dates on which a certain event occurs (so that I can bold them on a MonthCalendar control, or display them in some other way).

现在,对于可与常规功能(如果事件发生时每个星期一或每10天,例如)进行说明,这是没有问题的简单的时间间隔。

Now, for simple time intervals that can be described with regular functions (for instance if the event occurs every Monday or every 10 days) this is not a problem.

当我有不规则发生的事件(例如,如果事件发生在每周五,如果该月的第一天是星期二和那种事件)发生真正的问题。

The real problem occurs when I have an event with irregular occurrences (for instance if event occurs every Friday if the first day of the month is Tuesday and that kind of events).

既然不能预测该条件的格式,或者需要满足的条件连号的,我需要找到如何改变的方式条件(S)适当的内部if语句在运行时。

Since I can't predict the format of that condition's, or even the number of conditions that need to be met, I need to find a way on how to change the condition(s) inside the appropriate if statement during run-time.

事件的定义存储在SQL数据库。现在我的想法是使用一个列表,它的每个元素是一个条件,然后将它们传递给适当的if语句(如果有多个语句),或将其连接成一个字符串,并传递给适当的if语句。

The definitions of events are stored in a SQL database. Now my idea is to use a List whose every element would be one condition, and then pass them to appropriate if statements (if there are multiple statements) or join them into one string and pass to the appropriate if statement.

时的这种做法有可能,我会怎么做,或者我需要找到另一种方法,在这种情况下,请给我一个建议。

Is this approach possible, and how would I do it, or do I need to find another way, in which case please give me a suggestion.

感谢

推荐答案

您可以使用泛型委托谓词< T> ; 。 (请参见谓词(T)代表在MSDN)

You can use generic delegate Predicate<T>. (See Predicate(T) Delegate on MSDN)

谓词< IConditionParameters> 将返回布尔值, IConditionParemeters 抽象一组条件参数和代表本身封装了返回值的计算逻辑

Predicate<IConditionParameters> will return boolean value, IConditionParemeters abstracts a set of condition parameters and delegate itself encapsulates a logic for return value computation.

public class SimpleConditionParameters : IConditionParameters
{
   public int XValue { get; set; }
}

public class ComplexConditionParameters : IConditionParameters
{
   public int XValue { get; set; }

   public int YValue { get; set; }

   public bool SomeFlag { get; set; }
}

var conditions = new List<Predicate<IConditionParameters>>();
Predicate<SimpleConditionParameters> simpleCondition = (p) => 
{
   return p.XValue > 0;
};

Predicate<ComplexConditionParameters> complexCondition = (p) => 
{
   return p.SomeFlag && p.XValue > 0 && p.YValue < 0;
};

conditions.Add(simpleCondition);
conditions.Add(complexCondition);

这篇关于动态改变在C#中的if语句的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆