简体   繁体   中英

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

是否有与VB6的Choose()函数相当的C#?

day = Choose(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...

我会sugest,你使用DateTime.DaysInMonth代替:)

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM