简体   繁体   中英

What is the best way to get a multiple of a TimeSpan

There is an operation in a program that will take up to 'n' times longer than another operation (so I need to wait 'n' times longer before failing). The timeout for the other operation is saved as a TimeSpan. How do I get (OtherOperation.TimeSpan * 'n')?

You might consider writing an extension method, such as:

public static class TimeSpanEx
{
    public static TimeSpan MultiplyBy (this TimeSpan t, int multiplier)
    {
        return new TimeSpan(t.Ticks * multiplier);
    }
}

Now you can simply call:

TimeSpan result = yourtimespan.MultiplyBy(3);

As an aside, it would be really nice if one could just overload the * operator in an extension method, but this is currently not possible .

Are we talking .net?

If so use create a new timespan using timespan.frommilliseconds and pass in the original .totalmilliseconds value multiplied by your constant.

Hope that helps

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