共用方式為


使用 InvariantCulture 屬性

更新:2007 年 11 月

InvariantCulture 屬性代表既非中性也非特定的文化特性。它代表文化特性的第三種類型,而且是不區分文化特性。它與英文相關聯,但與國家或地區無關。您的應用程式可將這個屬性用於需要文化特性的 System.Globalization 命名空間中的幾乎所有方法。不過,應用程式應該只對需要與文化特性無關之結果的處理序,才使用不區分的文化特性,例如格式化和剖析保存至檔案的資料。在其他狀況下,它產生的結果可能會語法不正確或者不適用於文化特性。

安全性考量

如果將根據字串比較或大小寫變更的結果產生安全性決策,應用程式應使用會忽略大小寫的序數比較,而不使用 InvariantCulture。Compare() 和 ToUpper 等方法的預設實作會使用 CurrentCulture 屬性。如果 CurrentCulture 變更,或如果執行程式碼的電腦上的文化特性異於用來測試程式碼的文化特性,執行區分文化特性字串作業的程式碼可能會造成安全性弱點。您所預期寫入字串作業的行為將異於執行電腦上程式碼的實際行為。相反地,序數比較只會單獨視所比較字元的二進位值而定。

字串作業

如果您的應用程式需要區分文化特性的字串作業,但不要受 CurrentCulture 值的影響,則應使用接受 CultureInfo 參數的方法。應用程式應指定為這個參數指定 InvariantCulture 屬性值。應用程式應將屬性與 Compare() 和 ToUpper 等方法一起使用,以降低文化特性變化並確保一致的結果。如需使用 InvariantCulture 屬性執行不區分文化特性字串作業的詳細資訊,請參閱不區分文化特性的字串作業

保存資料

InvariantCulture 屬性適用於儲存不會直接顯示給使用者的資料。在與文化特性無關格式中儲存資料可保證已知的格式不會變更。當來自不同文化特性的使用者存取資料時,它可以根據特定使用者適當地進行格式化。例如,如果您的應用程式將 DateTime 型別儲存為文字檔並將其格式化為不因文化特性而異,則應用程式在呼叫 ToString 儲存字串以及呼叫 Parse 方法擷取字串時,應使用 InvariantCulture 屬性。此方式可確保在使用者從不同文化特性讀取或寫入時,DateTime 型別的基礎值不會改變。

下列程式碼範例會示範如何使用空字串 ("") 或 InvariantCulture,以不因文化特性而異的方式初始化 CultureInfo 物件。

' The following lines are equivalent.
CultureInfo Invc = New CultureInfo("")
CultureInfo Invc = CultureInfo.InvariantCulture
// The following lines are equivalent.
CultureInfo Invc = New CultureInfo("");
CultureInfo Invc = CultureInfo.InvariantCulture;

下列程式碼範例示範將 DateTime 物件寫入檔案,成為使用 ToString 方法格式化為不因文化特性而異的字串。該字串將從格式為不因文化特性而異的檔案讀取,並使用 Parse 方法剖析為 DateTime 物件。DateTime 物件接著會格式化並顯示為文化特性 "fr-FR" 和 "ja-JP"。

Imports System
Imports System.IO
Imports System.Globalization
Imports Microsoft.VisualBasic

Public Class TextToFile
   Private const FILE_NAME As String = "MyDateFile.txt"   
   
   Public Shared Sub Main()
      If File.Exists(FILE_NAME) Then
         Console.WriteLine("{0} already exists!", FILE_NAME)
         Return
      End If

      Dim sw As StreamWriter = File.CreateText(FILE_NAME)
      
      'Creates a DateTime.
      Dim dtIn As DateTime = DateTime.Now
      Dim InvC As CultureInfo = CultureInfo.InvariantCulture
      ' Writes the string to the file formatted for InvariantCulture.
      sw.WriteLine(dtIn.ToString("d", InvC))
      sw.Close()
      
      If Not File.Exists(FILE_NAME) Then
         Console.WriteLine("{0} does not exist!", FILE_NAME)
         Return
      End If
      
      Dim sr As StreamReader = File.OpenText(FILE_NAME)
      Dim filedate As String
      filedate = sr.Readline()
      While Not filedate Is Nothing
         Console.WriteLine(ControlChars.Newline + "The date stored in _
            the file formatted for the invariant culture is:" + _
            ControlChars.Newline + " {0}", filedate )
         
         ' Creates a new DateTime and parses the 
         ' string stored in the file.
         Dim dtout as DateTime = DateTime.Parse(filedate, InvC)
         
         ' Creates a CultureInfo set to "fr-FR".
         Dim frc As New CultureInfo("fr-FR")
         ' Displays the date formatted for the "fr-FR" culture.
         Console.WriteLine(ControlChars.Newline + "The date read from _
            the file and formatted for the culture ""fr-FR"" is:" + _
            ControlChars.Newline + " {0}", dtout.ToString("d", frc))
         
         ' Creates a CultureInfo set to "ja-JP".
         Dim jpn As New CultureInfo("ja-JP")
         ' Displays the date formatted for the "ja-JP" culture.
         Console.WriteLine(ControlChars.Newline + "The date read from _
            the file and formatted for the culture ""ja-JP"" is:" + _
            ControlChars.Newline + " {0}", dtout.ToString("d", jpn))
        
        filedate = sr.Readline()
      End While
      
      Console.WriteLine(ControlChars.Newline + "The end of the stream _
         has been reached.")
      sr.Close()
   End Sub
End Class
using System;
using System.IO;
using System.Globalization;

public class TextToFile 
{
   private const string FILE_NAME = "MyDateFile.txt";
   public static void Main(String[] args) 
   {
      if (File.Exists(FILE_NAME)) 
      {
         Console.WriteLine("{0} already exists!", FILE_NAME);
         return;
      }
      StreamWriter sw = File.CreateText(FILE_NAME);
      
      // Creates a DateTime.      
      DateTime dtIn = DateTime.Now;
      // Creates a CultureInfo set to InvariantCulture.
      CultureInfo InvC = new CultureInfo("");
      // Converts dt to a string formatted for InvariantCulture,
      // and writes it to a file.
      sw.WriteLine (dtIn.ToString("d",InvC));
      sw.Close();

      if (!File.Exists(FILE_NAME)) 
      {
         Console.WriteLine("{0} does not exist!", FILE_NAME);
         return;
      }
      StreamReader sr = File.OpenText(FILE_NAME);
      String date;
      while ((date=sr.ReadLine())!=null) 
      {
         Console.WriteLine("\nThe date stored in the file formatted for 
               the invariant culture is:\n{0}" , date);    

         // Parses the string stored in the file,
         // and stores it in a DateTime.
         DateTime dtout = DateTime.Parse(date, InvC);

         // Creates a CultureInfo set to "fr-FR".
         CultureInfo frc = new CultureInfo("fr-FR");
         // Displays the date formatted for the "fr-FR" culture.
         Console.WriteLine("\nThe date read from the file and formatted 
               for the culture \"fr-FR\" is:\n{0}" , dtout.ToString("d", 
               frc));

         // Creates a CultureInfo set to "ja-JP".
         CultureInfo jpn= new CultureInfo("ja-JP");
         // Displays the date formatted for the "ja-JP" culture.
         Console.WriteLine("\nThe date read from the file and formatted 
               for the culture \"ja-JP\" is:\n{0}" , dtout.ToString("d", 
               jpn));
      }
      Console.WriteLine ("\nThe end of the stream has been reached.");
      sr.Close();
   }
}

這個程式碼產生下列輸出:

The date stored in the file formatted for the invariant culture is:
07/24/2001

The date read from the file and formatted for the culture "fr-FR" is:
24/07/2001

The date read from the file and formatted for the culture "ja-JP" is:
2001/07/24

The end of the stream has been reached.

請參閱

概念

使用 CultureInfo 類別