调用其他扩展方法的扩展方法

Extension method calling other extension wethod

我一直在尝试编写一个扩展方法来生成带有正确时区和格式的日期时间的字符串。我的代码是:

public static class DateTimeExtension
{
    public static string ToZoneString(this DateTime date, string zoneId, string formatter)
    {
        TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
        return TimeZoneInfo.ConvertTime(date, zone).ToString(formatter);
    }

    public static string ToZoneString(this DateTimeOffset date, string zoneId, string formatter)
    {   
        //in this case all goes well
        //TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
        //return TimeZoneInfo.ConvertTime(date, zone).ToString(formatter); 

        //in this case an unexpected error occurs        
        return date.ToZoneString(zoneId, formatter);
    }
} 

但是在编译之后 运行 我的 ASP.NET MVC 项目

"An unhandled Microsoft .Net Framework exception occured in w3wp.exe"

发生了。为什么会这样?如果我不在第二个方法中调用第一个方法,而只调用相同的方法,所有方法都会正确执行。

我认为,如果您以这种方式更新第二种方法,它将适用于您:

public static string ToZoneString(this DateTimeOffset date, string zoneId, string formatter)
{   
    //in this case all goes well
    //TimeZoneInfo zone = TimeZoneInfo.FindSystemTimeZoneById(zoneId);
    //return TimeZoneInfo.ConvertTime(date, zone).ToString(formatter); 

    //in this case an unexpected error occurs        
    return date.DateTime.ToZoneString(zoneId, formatter);
}

但根据您的需要,您可以选择不同的方法从 DateTimeOffset(LocalDateTime, UtcDateTime)

获取 DateTime

你的第二个方法没有调用你的第一个,它只是再次调用你的第二个。再次调用你的第二个。再次调用你的第二个。依此类推,直到您的整个进程因 WhosebugException.

而崩溃

您永远不会调用第一个方法。您的第二个方法调用 自身 。如果您想调用第一个方法,您需要先将 DateTimeOffset 转换为 DateTime