[英]C# switch case forcing
嗨,我正在制作一個 C# windows 窗體應用程序,我切換了我所有隊友的生日以計算他們的生日年齡,但是我想添加一個功能,如果今天是他們的生日,則會出現一條消息。 因此,我需要在開關的 EACH CASE 中添加一些內容,然后我將添加一個驗證,例如今天的日期是否等於 bday,然后消息顯示“它的名字 1 歲生日,今天!”
switch (name)
{
case "name 1":
bday = DateTime.Parse("11.11.1988");
break;
case "name 2":
bday = DateTime.Parse("11.12.1988");
break;
case "name 3":
bday = DateTime.Parse("03.12.1987");
break;
}
你為什么不使用字典。 字典使用其他對象作為鍵來檢索它們的值。
在您的情況下,您可以將所有生日映射到他們的名字,例如:
Dictionary<string, DateTime> birthdays = new Dictionary<string, DateTime>;
//Add values like this
birthdays.Add("name 1", DateTime.Parse("11.11.1988"));
birthdays.Add("name 2", DateTime.Parse("11.12.1988"));
...
//Then you could loop through all the entries
foreach(KeyValuePair<string, DateTime> entry in birthdays)
{
if(entry.Value.Day == DateTime.Now.Day && entry.Value.Month == DateTime.Now.Month)
{
Console.WriteLine(entry.Key + " has birthday!");
}
}
根據您在代碼段中提供的內容,您可以在 case 語句之外進行此類檢查。 例子:
public void WhateverYourMethodIs()
{
switch (name)
{
case "name 1":
bday = DateTime.Parse("11.11.1988");
break;
case "name 2":
bday = DateTime.Parse("11.12.1988");
break;
case "name 3":
bday = DateTime.Parse("03.12.1987");
break;
}
if (this.IsBirthday(bday))
{
// do whatever you want for when it's the name's birthday.
}
}
public bool IsBirthday(DateTime bday)
{
if (bday.Day == DateTime.Now.Day && bday.Month == DateTime.Now.Month)
return true;
return false;
}
請注意,以上不會考慮閏日生日。
根據您的評論,您似乎希望在不考慮切換的情況下評估所有姓名的生日。 這在您當前的方法中不起作用。 bday
是一個只能歸因於當前“名稱”的單一值。
實現您希望的一種方法是使用類來表示名稱,如下所示:
public class User
{
public string Name { get; set; }
public DateTime Birthday { get; set; }
public bool IsBirthday
{
get
{
if (Birthday.Day == DateTime.Now.Day && Birthday.Month == DateTime.Now.Month)
return true;
return false;
}
}
}
public class SomeClass
{
private List<User> Users = new List<User>();
public void PopulateNames()
{
Users.Add(new User()
{
Name = "name 1",
Birthday = DateTime.Parse("11.11.1988")
};
Users.Add(new User()
{
Name = "name 2",
Birthday = DateTime.Parse("11.12.1988")
};
// etc
}
public void DoSomethingOnUsersWithABirthday()
{
foreach (User user in Users)
{
if (user.IsBirthday)
{
// do something for their birthday.
Console.WriteLine(string.format("It's {0}'s birthday!", user.Name));
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.