İngilizce dilinde oku

Aracılığıyla paylaş


IFormatProvider Arabirim

Tanım

Biçimlendirmeyi denetlemek için nesne almaya yönelik bir mekanizma sağlar.

C#
public interface IFormatProvider
C#
[System.Runtime.InteropServices.ComVisible(true)]
public interface IFormatProvider
Türetilmiş
Öznitelikler

Örnekler

Aşağıdaki örnekte, bir IFormatProvider uygulamanın tarih ve saat değerinin gösterimini nasıl değiştirebileceği gösterilmektedir. Bu durumda, dört farklı kültürü temsil eden nesneler kullanılarak CultureInfo tek bir tarih görüntülenir.

C#
using System;
using System.Globalization;

public class Example
{
   public static void Main()
   {
      DateTime dateValue = new DateTime(2009, 6, 1, 16, 37, 0);
      CultureInfo[] cultures = { new CultureInfo("en-US"),
                                 new CultureInfo("fr-FR"),
                                 new CultureInfo("it-IT"),
                                 new CultureInfo("de-DE") };
      foreach (CultureInfo culture in cultures)
         Console.WriteLine("{0}: {1}", culture.Name, dateValue.ToString(culture));
   }
}
// The example displays the following output:
//       en-US: 6/1/2009 4:37:00 PM
//       fr-FR: 01/06/2009 16:37:00
//       it-IT: 01/06/2009 16.37.00
//       de-DE: 01.06.2009 16:37:00

Aşağıdaki örnekte arabirimini ve yöntemini uygulayan bir sınıfın IFormatProvider kullanımı gösterilmektedir GetFormat . sınıfı, AcctNumberFormat hesap numarasını temsil eden bir Int64 değeri biçimlendirilmiş 12 basamaklı hesap numarasına dönüştürür. GetFormat parametresi uygulayan ICustomFormatterbir sınıfa başvuruyorsa formatType yöntemi geçerli AcctNumberFormat örneğe bir başvuru döndürür; aksi takdirde döndürür GetFormat null.

C#
public class AcctNumberFormat : IFormatProvider, ICustomFormatter
{
   private const int ACCT_LENGTH = 12;

   public object GetFormat(Type formatType)
   {
      if (formatType == typeof(ICustomFormatter))
         return this;
      else
         return null;
   }

   public string Format(string fmt, object arg, IFormatProvider formatProvider)
   {
      // Provide default formatting if arg is not an Int64.
      if (arg.GetType() != typeof(Int64))
         try {
            return HandleOtherFormats(fmt, arg);
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
         }

      // Provide default formatting for unsupported format strings.
      string ufmt = fmt.ToUpper(CultureInfo.InvariantCulture);
      if (! (ufmt == "H" || ufmt == "I"))
         try {
            return HandleOtherFormats(fmt, arg);
         }
         catch (FormatException e) {
            throw new FormatException(String.Format("The format of '{0}' is invalid.", fmt), e);
         }

      // Convert argument to a string.
      string result = arg.ToString();

      // If account number is less than 12 characters, pad with leading zeroes.
      if (result.Length < ACCT_LENGTH)
         result = result.PadLeft(ACCT_LENGTH, '0');
      // If account number is more than 12 characters, truncate to 12 characters.
      if (result.Length > ACCT_LENGTH)
         result = result.Substring(0, ACCT_LENGTH);

      if (ufmt == "I")                    // Integer-only format.
         return result;
      // Add hyphens for H format specifier.
      else                                         // Hyphenated format.
         return result.Substring(0, 5) + "-" + result.Substring(5, 3) + "-" + result.Substring(8);
   }

   private string HandleOtherFormats(string format, object arg)
   {
      if (arg is IFormattable)
         return ((IFormattable)arg).ToString(format, CultureInfo.CurrentCulture);
      else if (arg != null)
         return arg.ToString();
      else
         return String.Empty;
   }
}

Uygulayan IFormatProvider sınıf daha sonra bir biçimlendirme ve ayrıştırma işlemi çağrısında kullanılabilir. Örneğin, aşağıdaki kod biçimlendirilmiş 12 basamaklı hesap numarası içeren bir dize oluşturmak için yöntemini çağırır String.Format(IFormatProvider, String, Object[]) .

C#
using System;
using System.Globalization;

public enum DaysOfWeek { Monday=1, Tuesday=2 };

public class TestFormatting
{
   public static void Main()
   {
      long acctNumber;
      double balance;
      DaysOfWeek wday;
      string output;

      acctNumber = 104254567890;
      balance = 16.34;
      wday = DaysOfWeek.Monday;

      output = String.Format(new AcctNumberFormat(),
                             "On {2}, the balance of account {0:H} was {1:C2}.",
                             acctNumber, balance, wday);
      Console.WriteLine(output);

      wday = DaysOfWeek.Tuesday;
      output = String.Format(new AcctNumberFormat(),
                             "On {2}, the balance of account {0:I} was {1:C2}.",
                             acctNumber, balance, wday);
      Console.WriteLine(output);
   }
}
// The example displays the following output:
//       On Monday, the balance of account 10425-456-7890 was $16.34.
//       On Tuesday, the balance of account 104254567890 was $16.34.

Açıklamalar

Arabirim, IFormatProvider biçimlendirme ve ayrıştırma işlemleri için biçimlendirme bilgileri sağlayan bir nesne sağlar. Biçimlendirme işlemleri, bir türün değerini bu değerin dize gösterimine dönüştürür. Tipik biçimlendirme yöntemleri, hem bir türün yöntemleri hem de FormatyöntemleridirToString. Ayrıştırma işlemleri, bir değerin dize gösterimini bu değere sahip bir türe dönüştürür. Tipik ayrıştırma yöntemleri ve TryParse'tirParse.

IFormatProvider Arabirimi tek bir yöntemden oluşur: IFormatProvider.GetFormat. GetFormat bir geri çağırma yöntemidir: Ayrıştırma veya biçimlendirme yöntemi onu çağırır ve biçimlendirme veya ayrıştırma yönteminin biçimlendirme bilgilerini sağlayacağı nesne türünü temsil eden bir Type nesne geçirir. yöntemi GetFormat , bu türdeki bir nesneyi döndürmekten sorumludur.

IFormatProvider uygulamaları genellikle biçimlendirme ve ayrıştırma yöntemleri tarafından örtük olarak kullanılır. Örneğin, DateTime.ToString(String) yöntemi örtük olarak sistemin geçerli kültürünü temsil eden bir IFormatProvider uygulama kullanır. IFormatProvideruygulamaları, ve String.Format(IFormatProvider, String, Object[])gibi Int32.Parse(String, IFormatProvider) türünde IFormatProviderbir parametreye sahip yöntemler tarafından açıkça belirtilebilir.

.NET Framework, sayısal ve tarih ve saat değerlerini biçimlendirmek veya ayrıştırmak için kullanılan kültüre özgü bilgiler sağlamak için aşağıdaki önceden tanımlanmış IFormatProvider üç uygulamayı içerir:

.NET Framework özel biçimlendirmeyi de destekler. Bu genellikle hem ICustomFormatterhem de IFormatProvider uygulayan bir biçimlendirme sınıfı oluşturmayı içerir. Daha sonra bu sınıfın bir örneği, bir sayıyı 12 basamaklı hesap numarası olarak biçimlendiren böyle bir özel uygulamanın çizimini sağlar gibi String.Format(IFormatProvider, String, Object[]) özel biçimlendirme işlemi gerçekleştiren bir yönteme parametre olarak geçirilir.

Yöntemler

GetFormat(Type)

Belirtilen tür için biçimlendirme hizmetleri sağlayan bir nesne döndürür.

Şunlara uygulanır

Ürün Sürümler
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

Ayrıca bkz.