共用方式為


使用 InvariantCulture 屬性

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

安全性考量

如果將根據字串比較或大小寫變更的結果產生安全性決策,請使用會忽略大小寫的序數比較,而不使用 InvariantCulture。這是因為方法 (例如 String.CompareString.ToUpperString.ToLower) 的預設實作都會使用 CultureInfo.CurrentCulture 屬性。如果 CultureInfo.CurrentCulture 變更,或如果程式碼執行所在電腦上的文化特性異於開發人員用來測試程式碼的文化特性,執行區分文化特性字串作業的程式碼可能會造成安全性弱點。開發人員所預期寫入字串作業的行為將異於作業執行所在電腦上的程式碼實際行為。相反地,序數比較只會單獨視所比較字元的二進位值而定。

字串作業

如果您要執行不受 CultureInfo.CurrentCulture 值所影響之會區分文化特性的字串作業,請使用可接受 CultureInfo 參數的方法,對 CultureInfo 參數指定 CultureInfo.InvariantCulture 屬性的值。與方法 (例如 String.CompareString.ToUpperString.ToLower) 一起使用 InvariantCulture,以降低文化特性變化並確保一致的結果。如需使用 InvariantCulture 屬性以執行不區分文化特性字串作業的詳細資訊,請參閱不區分文化特性的字串作業

保存資料

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

下列程式碼範例會示範如何使用空字串 ("") 或 CultureInfo.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 寫入檔案,成為使用 DateTime.ToString 方法格式化為 InvariantCulture 的字串。該字串將從格式為 InvariantCulture 的檔案讀取,並使用 Date.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 Class
CultureInfo.CurrentUICulture Property
CultureInfo.CreateSpecificCulture Method

其他資源

編碼和當地語系化