尝试在消息框中设置名称,具体取决于 DateTime.now

Trying to set a name in a messagebox, depending on DateTime.now

为了简短起见,我想根据日期填写姓名。 我没有使用任何数据库,它是纯 C#。

低于我当前的代码。

DateTime dt = DateTime.Now;
string vandaag = dt.ToString("dd-MM-yyyy");
string bday = " has his/her birthday today";

Boolean name1 = DateTime.Now.Month == 3 && DateTime.Now.Day == 12;
Boolean name2 = DateTime.Now.Month == 6 && DateTime.Now.Day == 9;

if (name1) {MessageBox.Show(string.Format("Hello, today is {0}. name of person 1 {1}", today, bday), "Hello", MessageBoxButtons.OK);}

else if (name2) {MessageBox.Show(string.Format("Hello, today is {0}. name of person 2 {1}", today, bday), "Hello", MessageBoxButtons.OK);}

等等

该代码确实有效,但像这样我要为几乎所有人重复这段代码。有没有办法不用一遍又一遍地重复相同的代码就可以填入 "name of person"?

我通常会创建一个列表<>对象,这样我就可以枚举表单上的控件

        public List<TextBox> boxes = null;
        public Form1()
        {
            InitializeComponent();

            boxes = new List<TextBox>() { textBox1, textBox2, textBox3, textBox4};

            foreach (TextBox box in boxes)
            {
            }

在这种情况下使用 Dictionay Class 很有用,请看这个例子:

public void sayHappyBirthDay(Dictionary<string, DateTime> nameBirthDay)
{
    DateTime today = DateTime.Now;
    foreach (var n in nameBirthDay)
    {
        if (today.Month == n.Value.Month && today.Day == n.Value.Day)
        {
            string bday = n.Key;
            MessageBox.Show(string.Format("Hello, today is {0}. name of person: {1}", today, bday), "Hello", MessageBoxButtons.OK);
        }
    }
}

你可以这样做(未经测试,直接写在 Stack Overflow 上,小心处理 我花时间测试它 made a fiddle...令人惊讶的是只出现了小错误!):

static void AddBirthdayToDictionary(Dictionary<DateTime, List<string>> dict, int month, int day, string name)
{
  var bdate = new DateTime(DateTime.MinValue.Year, month, day);
  List<string> val;
  if(!dict.TryGetValue(bdate, out val))
  {
    val = new List<string>();
    dict.Add(bdate, val);
  }
  val.Add(name);
}

static List<string> GetBirthdays(Dictionary<DateTime, List<string>> dict, int month, int day)
{
  var bdate = new DateTime(DateTime.MinValue.Year, month, day);
  List<string> val;
  if(dict.TryGetValue(bdate, out val))
  {
    return val;
  }
  return new List<string>();
}

static void ShowBirthdays()
{
    var birthdayDictionary = new Dictionary<DateTime, List<string>>();

    // add possible birthdays    
    AddBirthdayToDictionary(birthdayDictionary, 3, 12, "Person 1");
    AddBirthdayToDictionary(birthdayDictionary, 6, 9, "Person 2");

    var today = DateTime.Today;

    // get birthdays today
    var bdayList = GetBirthdays(birthdayDictionary, today.Month, today.Day);

    if(bdayList.Any())
    {
        var count = bdayList.Count();
        MessageBox.Show(string.Format("Hello, today is {0} and {1} {2} celebrating {3} birthday!", today, string.Join(", ", bdayList), (count>1) ? "are":"is", (count>1) ? "their" : "its"));   
    }       
}

首先要做的就是像这样定义一个Personclass(以后可以扩展)

public class Person
{
    public string Name { get; set; }
    public DateTime dob {get;set;}
}

然后你需要建立一个你想要检查他们生日的人的列表

List<Person> people = new List<Person>()
{
    new Person() {Name="Steve", dob = new DateTime(1960, 3, 26)},
    new Person() {Name="John", dob = new DateTime(1961, 7, 1)},
};

最后,您的代码可以使用简单的 linq 代码搜索今天是否是任何人列表的出生日期

Person p = people.FirstOrDefault(x => x.dob.Month == DateTime.Today.Month && 
                                      x.dob.Day == DateTime.Today.Day);
if (p != null)
    MessageBox.Show(string.Format("Hello, today is {0}. Birthday of person {1}", DateTime.Today, p.Name), "Hello", MessageBoxButtons.OK); 

使用这种方法,您只需使用上述格式将其他人添加到列表中,其他任何内容都不会改变。但是有一个问题,因为您可能有多个具有相同出生日期的人。在这种情况下,搜索列表的代码变为

List<Person> ppl = people.Where(x => x.dob.Month == DateTime.Today.Month && 
                                x.dob.Day == DateTime.Today.Day).ToList();
MessageBox.Show(string.Format("There are {0} people with this dob", ppl.Count));
foreach(Person p in ppl)
    MessageBox.Show(string.Format("Hello, today is {0}. Birthday of person {1}", DateTime.Today, p.Name), "Hello", MessageBoxButtons.OK); 

有了@Steve 给出的出色答案,我只想指出使用 string[,] 的二维数组实现基本相同功能的简单得多(不需要 OOP、LINQ、泛型):

// out message
string _msg = String.Empty;

// sample array of Name/Birthday
string[,] _bd = { 
                    { "Tom", "03/26/2016" }, 
                    { "Gary", "06/27/2016" }, 
                    { "Anna", "04/30/2016" } 
                };
for (int i = 0; i < _bd.GetLength(0); i++)
{
    if (DateTime.Today == DateTime.Parse(_bd[i, 1]))
    {
        // output message containing list of names
        _msg += _bd[i, 0] + ",";
    }
}
if (!String.IsNullOrEmpty(_msg)) MessageBox.Show("Hello" +_msg);

此代码片段可以进一步customized/optimized,例如,使用TryParse(), StringBuilder