如何将DateTimeFormatInfo.CurrentInfo和NumberFormatInfo.CurrentInfo设置为不变式?

时间:2019-03-27 07:37:43

标签: c# .net .net-core cultureinfo

我正在重构一些单元测试,发现某些解析策略依赖于DateTime.TryParseExactsbyte.TryPase,而它们本身依赖于NumberFormatInfo.CurrentInfoDateTimeFormatInfo.CurrentInfo

为了使我的单元测试正确安排,我决定通过以下方式将CurrentInfoNumberFormatInfo的{​​{1}}属性设置为其不变的风格:

DateTimeFormatInfo

但是,出于好奇,我试图通过单元测试来检查各个CultureInfo.CurrentCulture = CultureInfo.InvariantCulture; 是否已设置,但事实并非如此。我想知道在这两个InvariantInfo

中强制执行InvariantCulture的问题
CurrentInfo

了解基本实现:

[Fact] public void ShouldReturnInvariantInfo() { CultureInfo.CurrentCulture.NumberFormat = NumberFormatInfo.InvariantInfo; CultureInfo.CurrentCulture.DateTimeFormat = DateTimeFormatInfo.InvariantInfo; NumberFormatInfo.CurrentInfo.Should().Be(NumberFormatInfo.InvariantInfo); DateTimeFormatInfo.CurrentInfo.Should().Be(DateTimeFormatInfo.InvariantInfo); }

NumberFormatInfo.InvariantInfo

public static NumberFormatInfo CurrentInfo { get { CultureInfo currentCulture = CultureInfo.CurrentCulture; if (!currentCulture._isInherited) { NumberFormatInfo numInfo = currentCulture.numInfo; if (numInfo != null) return numInfo; } return (NumberFormatInfo) currentCulture.GetFormat(typeof (NumberFormatInfo)); } }

DateTimeFormatInfo.CurrentInfo

1 个答案:

答案 0 :(得分:3)

如果我理解正确,那么您想在Current的区域性下运行一些代码(测试),但NumberFormatDateTimeFormat除外。如果您遇到这种情况,建议您Invariant当前的区域性并修改克隆:

Clone

让我们来看看格式

// Current culture clone
CultureInfo testCulture = CultureInfo.CurrentCulture.Clone() as CultureInfo;

// modified: current culture except Number and DateTime which are Invariant
testCulture.NumberFormat = CultureInfo.InvariantCulture.NumberFormat;
testCulture.DateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;

// and, finally, set back as current
CultureInfo.CurrentCulture = testCulture;

结果:

Console.Write(ReferenceEquals(CultureInfo.CurrentCulture.DateTimeFormat,
                              CultureInfo.InvariantCulture.DateTimeFormat) 
     ? "Equals" 
     : "Not Equals");

编辑:为了运行修改后的区域性代码Equals ,我们可以为其实现一个 class

using

然后按如下所示使用它:

  public class TestCulture : IDisposable {
    private CultureInfo m_SavedCulture; 
    private CultureInfo m_TestCulture;
    private bool m_IsDisposed;

    public TestCulture() {
      m_SavedCulture = CultureInfo.CurrentCulture; 

      m_TestCulture = CultureInfo.CurrentCulture.Clone() as CultureInfo;
      m_TestCulture.NumberFormat = CultureInfo.InvariantCulture.NumberFormat;
      m_TestCulture.DateTimeFormat = CultureInfo.InvariantCulture.DateTimeFormat;

      CultureInfo.CurrentCulture = m_TestCulture;
    }

    protected vitrual void Dispose(bool disposing) {
      if (disposing) {
        if (!m_IsDisposed && ReferenceEquals(CultureInfo.CurrentCulture, m_TestCulture)) {
          CultureInfo.CurrentCulture = m_SavedCulture;

          m_IsDisposed = true;
        }
      }
    }

    public void Dispose() => Dispose(true);
  }