开发者

Is there a C# equivalent of VB6's Choose() function?

开发者 https://www.devze.com 2022-12-23 19:03 出处:网络
Is there a C# equivalent of VB6\'s Choose() function? day = Ch开发者_JAVA百科oose(month,31,28,30)

Is there a C# equivalent of VB6's Choose() function?

day = Ch开发者_JAVA百科oose(month,31,28,30) 


Not really. You can of course create an array an use its indexed getter:

day = new[] { 31, 28, 30 }[month];

Alternatively, you could - I wouldn't - import the Microsoft.VisualBasic namespace and do:

day = Interaction.Choose(month, 31, 28, 30);

I do not know how much your example is simplified, but in the case that you are actually looking for a way to find the numbers of days in a specific month, try DateTime.DaysInMonth():

day = DateTime.DaysInMonth(2008, 2);
// day == 29


If it is really about the days in a month I would follow the advice others have given. However if you really need a Choose function you can easily build one yourself. For example like this:

public static T Choose<T>(int index, params T[] args)
{
    if (index < 1 || index > args.Length)
    {
        return default(T);
    }
    else
    {
        return args[--index];
    }
}

// call it like this
var day = Choose<int?>(1, 30, 28, 29);  // returns 30

I did not bother to make the first argument a double, but this can easily be done. It is also possible to make a non-generic version...


I will sugest, you use DateTime.DaysInMonth instead :)


My first guess will be

var days = new[] { 31, 28, 30 }[month];

Although native version does all sorts of crazy stuff, like rounding and kind-of-bounds-checking.


Simple answer: No.

If you are looking to do only what you sample is doing, try DateTime.DaysInMonth(year,month)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号