在我的代码中,我尝试处理ZoneLocalMapping.ResultType.Ambiguous。这条线
unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping;抛出带有消息“不应对类型不明确的结果调用EarlierMapping属性”的InvalidOperationException。
我不知道该怎么处理它。你能给我举个例子吗?
下面是我的代码:
public Instant getInstant(int year, int month, int day, int hour, int minute)
{
var localDateTime = new LocalDateTime(year, month, day, hour, minute); //invalidated, might be not existing
var timezone = DateTimeZone.ForId(TimeZoneId); //TimeZone is set elsewhere, example "Brazil/East"
var localDateTimeMapping = timezone.MapLocalDateTime(localDateTime);
ZonedDateTime unambiguousLocalDateTime;
switch (localDateTimeMapping.Type)
{
case ZoneLocalMapping.ResultType.Unambiguous:
unambiguousLocalDateTime = localDateTimeMapping.UnambiguousMapping;
break;
case ZoneLocalMapping.ResultType.Ambiguous:
unambiguousLocalDateTime = localDateTimeMapping.EarlierMapping;
break;
case ZoneLocalMapping.ResultType.Skipped:
unambiguousLocalDateTime = new ZonedDateTime(localDateTimeMapping.ZoneIntervalAfterTransition.Start, timezone);
break;
default:
throw new InvalidOperationException(string.Format("Unexpected mapping result type: {0}", localDateTimeMapping.Type));
}
return unambiguousLocalDateTime.ToInstant();
}如果我查看ZoneLocalMapping类,我会看到以下代码:
/// <summary>
/// In an ambiguous mapping, returns the earlier of the two ZonedDateTimes which map to the original LocalDateTime.
/// </summary>
/// <exception cref="InvalidOperationException">The mapping isn't ambiguous.</exception>
public virtual ZonedDateTime EarlierMapping { get { throw new InvalidOperationException("EarlierMapping property should not be called on a result of type " + type); } }这就是我收到异常的原因,但是我应该怎么做才能获得EarlierMapping呢?
发布于 2012-06-12 20:53:03
看起来您使用的是一个相对较旧的版本。从那时起,ZoneLocalMapping发生了一些变化,我怀疑我已经修复了您发现的错误。下面是一个有效的例子:
using System;
using NodaTime;
class Program
{
public static void Main()
{
var local = new LocalDateTime(2012, 10, 28, 1, 30, 0);
var zone = DateTimeZone.ForId("Europe/London");
var mapping = zone.MapLocal(local);
Console.WriteLine(mapping.Count); // 2
Console.WriteLine(mapping.First()); // 1.30 with offset +1
Console.WriteLine(mapping.Last()); // 1.30 with offest +0
}
}由于改进了“解析器”API,您的实际方法现在可以完全消失了。您现在可以使用:
private static readonly ZoneLocalResolver CustomResolver =
Resolvers.CreateMappingResolver(Resolvers.ReturnEarlier,
Resolvers.ReturnStartOfIntervalAfter);
...
Instant instant = zone.ResolveLocal(localDateTime, CustomResolver).ToInstant();https://stackoverflow.com/questions/10994948
复制相似问题