缩短代码 - DateTime& ELSE IF声明 - 让它变得动态

时间:2016-04-28 10:05:22

标签: c# datetime if-statement

我有一个很大的开始和结束日期时间列表来计算用户的星座。

如果用户的生日在此日期之间,则应用程序会吐出相关的星号。

我正在尝试将我的代码剪切到我可以使它,以便开发人员(我)可以输入额外的星号,而无需指定名称和日期。

例如:

(If UserBD >= DateStart && UserBD <= DateFinish)
{
  Console.WriteLine(“Your star sign is {0}”, StarSign);   
}

目前我有以下内容:

    DateTime AquariusStart = new DateTime(userBD.Year, 01, 20);
    DateTime AquariusEnd = new DateTime(userBD.Year, 02, 18);

    DateTime PiscesStart = new DateTime(userBD.Year, 02, 19);
    DateTime PiscesEnd = new DateTime(userBD.Year, 03, 20);


    if (userBD >= AquariusStart && userBD <= AquariusEnd)
    {
        Console.WriteLine("Your Star Sign is Aquarius!");
    }
    else if (userBD >= PiscesStart && userBD <= PiscesEnd)
    {
        Console.WriteLine("Your Star Sign is Pisces!");
    }

等等

我需要添加什么才能使代码“动态”?

提前致谢! :)

4 个答案:

答案 0 :(得分:0)

你需要这样的东西

public class StarSign
    {
        public string Name { get; set; }
        public DateTime Start { get; set; }
        public DateTime End { get; set; }
    }

    public class StarSignCalculator
    {
        public List<StarSign> Signs { get; set; }
        public StarSignCalculator()
        {
            Signs = new List<StarSign>();
            Signs.Add( new StarSign
            {
                Name = "Aquarius",
                Start = new DateTime(9999, 1,20),
                End = new DateTime(9999, 2, 18)
            } );
        }

        public StarSign GetStarSign( int month, int day )
        {
            var theDate = new DateTime( 9999, month, day );
            return Signs.FirstOrDefault( x => x.Start >= theDate && x.End <= theDate );
        }
    }

调用GetStartSign将返回Sign。请记住在标志列表中填写所有星标。

答案 1 :(得分:0)

我建议您创建一个词典或类似的东西,以保存一个独特的星座及其日期范围。这样您就可以根据日期范围选择标志。我创建了一个新的类Timelimit,它有两个DateTime属性来表示开始日期和结束日期。该类的定义如下:

class Timelimit
{
    public DateTime startDate { get; set; }
    public DateTime endDate { get; set; }
}

您可以通过向字典添加新元素来扩展字典。现在考虑下面的代码,这将解释其余的:

DateTime userBD = DateTime.Now; // let today be the b'day

Dictionary<string, Timelimit> ZodiacSigns = new Dictionary<string, Timelimit>();
ZodiacSigns.Add("Aquarius", new Timelimit()
{
    startDate = new DateTime(userBD.Year, 01, 20),
    endDate = new DateTime(userBD.Year, 02, 18)
});
ZodiacSigns.Add("Pisces", new Timelimit()
{
    startDate = new DateTime(userBD.Year, 03, 19),
    endDate = new DateTime(userBD.Year, 05, 20)
});
// Hence populate the dictonary from the developer side

string star = ZodiacSigns.Where(x => 
                          userBD >= x.Value.startDate && 
                          userBD <= x.Value.endDate)
                         .FirstOrDefault().Key

 Console.WriteLine("Your Star Sign is {0}!", star);

这将为Key提供相应日期范围的星号。

答案 2 :(得分:0)

我会将类StarSign实现为AquariusPisces类型的基类。然后,您可以填充已排序的List<StarSign>并使用LINQ查找第一个。

基本类型:

public class StarSign : IComparable<StarSign>
{
    public StarSign(string name, DateTime start, DateTime end)
    {
        if (start >= end) throw new ArgumentException("Start must be < end");
        this.Name = name;
        this.Start = start;
        this.End = end;
    }

    public string Name { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }

    public int CompareTo(StarSign other)
    {
        if (other == null) return 1;
        return Start.CompareTo(other.Start);
    }

    public bool IsStarSign(DateTime dt)
    {
        DateTime normalizedDate = new DateTime(this.Start.Year, dt.Month, dt.Day);
        return normalizedDate >= Start && normalizedDate <= End;
    }
}

可能的派生类型:

public class Aquarius : StarSign
{
    public Aquarius() : base("Aquarius", new DateTime(1, 01, 20), new DateTime(1, 02, 18))
    {
    }
}
public class Pisces : StarSign
{
    public Pisces() : base("Pisces", new DateTime(1, 02, 19), new DateTime(1, 03, 20))
    {
    }
}

然后剩下的代码非常简单和可维护:

List<StarSign> starSigns = new List<StarSign> { new Aquarius(), new Pisces() };
starSigns.Sort(); // only needed once and only if it's not added in the correct order

...

StarSign starSign = starSigns.First(s => s.IsStarSign(userBD));
Console.WriteLine("Your Star Sign is {0}!", starSign.Name);

答案 3 :(得分:0)

我设法使用此问题主题中其他用户发布的答案的各个部分来实现上述目标:

        List<StarSign> signList = new List<StarSign>()
        {
            new StarSign { startDate = new DateTime(userBD.Year, 01, 20), endDate = new DateTime(userBD.Year, 02, 18), signName = "Aquarius" },
            new StarSign { startDate = new DateTime(userBD.Year, 02, 19), endDate = new DateTime(userBD.Year, 03, 20), signName = "Pisces" },
            new StarSign { startDate = new DateTime(userBD.Year, 03, 21), endDate = new DateTime(userBD.Year, 04, 19), signName = "Aries" },
            new StarSign { startDate = new DateTime(userBD.Year, 04, 20), endDate = new DateTime(userBD.Year, 05, 20), signName = "Taurus" },
            new StarSign { startDate = new DateTime(userBD.Year, 05, 21), endDate = new DateTime(userBD.Year, 06, 20), signName = "Gemini" },
            new StarSign { startDate = new DateTime(userBD.Year, 06, 21), endDate = new DateTime(userBD.Year, 07, 22), signName = "Cancer" },
            new StarSign { startDate = new DateTime(userBD.Year, 07, 23), endDate = new DateTime(userBD.Year, 08, 22), signName = "Leo" },
            new StarSign { startDate = new DateTime(userBD.Year, 08, 23), endDate = new DateTime(userBD.Year, 09, 22), signName = "Virgo" },
            new StarSign { startDate = new DateTime(userBD.Year, 09, 23), endDate = new DateTime(userBD.Year, 10, 22), signName = "Libra" },
            new StarSign { startDate = new DateTime(userBD.Year, 10, 23), endDate = new DateTime(userBD.Year, 11, 21), signName = "Scorpio" },
            new StarSign { startDate = new DateTime(userBD.Year, 11, 22), endDate = new DateTime(userBD.Year, 12, 21), signName = "Sagittarius" },
            new StarSign { startDate = new DateTime(userBD.Year, 12, 22), endDate = new DateTime(userBD.Year + 1, 01, 19), signName = "Capricorn" }
        };

 for (int loopCounter = 0; loopCounter < signList.Count; loopCounter++)
 {
if (userBD >= signList[loopCounter].startDate && userBD <=  signList[loopCounter].endDate)
  {
     Console.WriteLine(signList[loopCounter].signName);
     break;
  }              
}

使用以下课程:

 class StarSign
    {
        public DateTime startDate { get; set; }
        public DateTime endDate { get; set; }
        public string signName { get; set; }
    }

感谢大家的帮助!