remove binary serialization examples from globalization article (#34842)

This commit is contained in:
Genevieve Warren 2023-03-31 07:48:13 -07:00 коммит произвёл GitHub
Родитель 392bb36bd1
Коммит 1bf68adb16
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
27 изменённых файлов: 448 добавлений и 711 удалений

Просмотреть файл

@ -45,9 +45,7 @@ The use of Unicode ensures that the same code units always map to the same chara
Even if you are developing an app that targets a single culture or region, you should use resource files to store strings and other resources that are displayed in the user interface. You should never add them directly to your code. Using resource files has a number of advantages:
- All the strings are in a single location. You don't have to search throughout your source code to identify strings to modify for a specific language or culture.
- There is no need to duplicate strings. Developers who don't use resource files often define the same string in multiple source code files. This duplication increases the probability that one or more instances will be overlooked when a string is modified.
- There's no need to duplicate strings. Developers who don't use resource files often define the same string in multiple source code files. This duplication increases the probability that one or more instances will be overlooked when a string is modified.
- You can include non-string resources, such as images or binary data, in the resource file instead of storing them in a separate standalone file, so they can be retrieved easily.
Using resource files has particular advantages if you are creating a localized app. When you deploy resources in satellite assemblies, the common language runtime automatically selects a culture-appropriate resource based on the user's current UI culture as defined by the <xref:System.Globalization.CultureInfo.CurrentUICulture%2A?displayProperty=nameWithType> property. As long as you provide an appropriate culture-specific resource and correctly instantiate a <xref:System.Resources.ResourceManager> object or use a strongly typed resource class, the runtime handles the details of retrieving the appropriate resources.
@ -155,9 +153,7 @@ You should never persist date and time data in a format that can vary by culture
You can avoid this problem in any of three ways:
- Serialize the date and time in binary format rather than as a string.
- Save and parse the string representation of the date and time by using a custom format string that is the same regardless of the user's culture.
- Save the string by using the formatting conventions of the invariant culture.
The following example illustrates the last approach. It uses the formatting conventions of the invariant culture returned by the static <xref:System.Globalization.CultureInfo.InvariantCulture%2A?displayProperty=nameWithType> property.
@ -169,7 +165,11 @@ The following example illustrates the last approach. It uses the formatting conv
A date and time value can have multiple interpretations, ranging from a general time ("The stores open on January 2, 2013, at 9:00 A.M.") to a specific moment in time ("Date of birth: January 2, 2013 6:32:00 A.M."). When a time value represents a specific moment in time and you restore it from a serialized value, you should ensure that it represents the same moment in time regardless of the user's geographical location or time zone.
The following example illustrates this problem. It saves a single local date and time value as a string in three [standard formats](../../standard/base-types/standard-date-and-time-format-strings.md) ("G" for general date long time, "s" for sortable date/time, and "o" for round-trip date/time) as well as in binary format.
The following example illustrates this problem. It saves a single local date and time value as a string in three [standard formats](../../standard/base-types/standard-date-and-time-format-strings.md):
- "G" for general date long time.
- "s" for sortable date/time.
- "o" for round-trip date/time.
[!code-csharp[Conceptual.Globalization#10](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates4.cs#10)]
[!code-vb[Conceptual.Globalization#10](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.globalization/vb/dates4.vb#10)]
@ -180,30 +180,22 @@ When the data is restored on a system in the same time zone as the system on whi
'3/30/2013 6:00:00 PM' --> 3/30/2013 6:00:00 PM Unspecified
'2013-03-30T18:00:00' --> 3/30/2013 6:00:00 PM Unspecified
'2013-03-30T18:00:00.0000000-07:00' --> 3/30/2013 6:00:00 PM Local
3/30/2013 6:00:00 PM Local
```
However, if you restore the data on a system in a different time zone, only the date and time value that was formatted with the "o" (round-trip) standard format string preserves time zone information and therefore represents the same instant in time. Here's the output when the date and time data is restored on a system in the Romance Standard Time zone:
```console
'3/30/2013 6:00:00 PM' --> 3/30/2013 6:00:00 PM Unspecified
'2013-03-30T18:00:00' --> 3/30/2013 6:00:00 PM Unspecified
'2013-03-30T18:00:00.0000000-07:00' --> 3/31/2013 3:00:00 AM Local
3/30/2013 6:00:00 PM Local
'3/30/2023 6:00:00 PM' --> 3/30/2023 6:00:00 PM Unspecified
'2023-03-30T18:00:00' --> 3/30/2023 6:00:00 PM Unspecified
'2023-03-30T18:00:00.0000000-07:00' --> 3/31/2023 3:00:00 AM Local
```
To accurately reflect a date and time value that represents a single moment of time regardless of the time zone of the system on which the data is deserialized, you can do any of the following:
- Save the value as a string by using the "o" (round-trip) standard format string. Then deserialize it on the target system.
- Convert it to UTC and save it as a string by using the "r" (RFC1123) standard format string. Then deserialize it on the target system and convert it to local time.
- Convert it to UTC and save it as a string by using the "u" (universal sortable) standard format string. Then deserialize it on the target system and convert it to local time.
- Convert it to UTC and save it in binary format. Then deserialize it on the target system and convert it to local time.
The following example illustrates each technique.
[!code-csharp[Conceptual.Globalization#11](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/dates8.cs#11)]
@ -212,11 +204,9 @@ The following example illustrates each technique.
When the data is serialized on a system in the Pacific Standard Time zone and deserialized on a system in the Romance Standard Time zone, the example displays the following output:
```console
'2013-03-30T18:00:00.0000000-07:00' --> 3/31/2013 3:00:00 AM Local
'Sun, 31 Mar 2013 01:00:00 GMT' --> 3/31/2013 3:00:00 AM Local
'2013-03-31 01:00:00Z' --> 3/31/2013 3:00:00 AM Local
3/31/2013 3:00:00 AM Local
'2023-03-30T18:00:00.0000000-07:00' --> 3/31/2023 3:00:00 AM Local
'Sun, 31 Mar 2023 01:00:00 GMT' --> 3/31/2023 3:00:00 AM Local
'2023-03-31 01:00:00Z' --> 3/31/2023 3:00:00 AM Local
```
For more information, see [Convert times between time zones](../../standard/datetime/converting-between-time-zones.md).
@ -233,9 +223,7 @@ For example, the transition from Pacific Standard Time to Pacific Daylight Time
To ensure that an arithmetic operation on date and time values produces accurate results, follow these steps:
1. Convert the time in the source time zone to UTC.
2. Perform the arithmetic operation.
3. If the result is a date and time value, convert it from UTC to the time in the source time zone.
The following example is similar to the previous example, except that it follows these three steps to correctly add 48 hours to March 9, 2013 at 10:30 A.M.
@ -268,13 +256,11 @@ The handling of numbers depends on whether they are displayed in the user interf
### Display numeric values
Typically, when numbers are displayed in the user interface, you should use the formatting conventions of the user's culture, which is defined by the <xref:System.Globalization.CultureInfo.CurrentCulture%2A?displayProperty=nameWithType> property and by the <xref:System.Globalization.NumberFormatInfo> object returned by the `CultureInfo.CurrentCulture.NumberFormat` property. The formatting conventions of the current culture are automatically used when you format a date by using any of the following methods:
Typically, when numbers are displayed in the user interface, you should use the formatting conventions of the user's culture, which is defined by the <xref:System.Globalization.CultureInfo.CurrentCulture%2A?displayProperty=nameWithType> property and by the <xref:System.Globalization.NumberFormatInfo> object returned by the `CultureInfo.CurrentCulture.NumberFormat` property. The formatting conventions of the current culture are automatically used when you format a date in the following ways:
- The parameterless `ToString` method of any numeric type
- The `ToString(String)` method of any numeric type, which includes a format string as an argument
- The [composite formatting](../../standard/base-types/composite-formatting.md) feature, when it is used with numeric values
- Using the parameterless `ToString` method of any numeric type.
- Using the `ToString(String)` method of any numeric type, which includes a format string as an argument.
- Using [composite formatting](../../standard/base-types/composite-formatting.md) with numeric values.
The following example displays the average temperature per month in Paris, France. It first sets the current culture to French (France) before displaying the data, and then sets it to English (United States). In each case, the month names and temperatures are displayed in the format that is appropriate for that culture. Note that the two cultures use different decimal separators in the temperature value. Also note that the example uses the "MMMM" custom date and time format string to display the full month name, and that it allocates the appropriate amount of space for the month name in the result string by determining the length of the longest month name in the <xref:System.Globalization.DateTimeFormatInfo.MonthNames%2A?displayProperty=nameWithType> array.
@ -291,17 +277,9 @@ You should never persist numeric data in a culture-specific format. This is a co
To avoid this problem, you can use one of these techniques:
- Save and parse the string representation of the number by using a custom format string that is the same regardless of the user's culture.
- Save the number as a string by using the formatting conventions of the invariant culture, which is returned by the <xref:System.Globalization.CultureInfo.InvariantCulture%2A?displayProperty=nameWithType> property.
- Serialize the number in binary instead of string format.
The following example illustrates the last approach. It serializes the array of <xref:System.Double> values, and then deserializes and displays them by using the formatting conventions of the English (United States) and French (France) cultures.
[!code-csharp[Conceptual.Globalization#7](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/numbers3.cs#7)]
[!code-vb[Conceptual.Globalization#7](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.globalization/vb/numbers3.vb#7)]
Serializing currency values is a special case. Because a currency value depends on the unit of currency in which it is expressed; it makes little sense to treat it as an independent numeric value. However, if you save a currency value as a formatted string that includes a currency symbol, it cannot be deserialized on a system whose default culture uses a different currency symbol, as the following example shows.
Serializing currency values is a special case. Because a currency value depends on the unit of currency in which it's expressed, it makes little sense to treat it as an independent numeric value. However, if you save a currency value as a formatted string that includes a currency symbol, it cannot be deserialized on a system whose default culture uses a different currency symbol, as the following example shows.
[!code-csharp[Conceptual.Globalization#16](../../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.globalization/cs/currency1.cs#16)]
[!code-vb[Conceptual.Globalization#16](../../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.globalization/vb/currency1.vb#16)]

Просмотреть файл

@ -5,7 +5,7 @@ using System.Text;
public class Example
{
public static void Main()
public static void CodePages()
{
// Represent Greek uppercase characters in code page 737.
char[] greekChars =
@ -43,6 +43,7 @@ public class Example
Console.WriteLine(data);
}
}
// The example displays the following output:
// ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩ
// €‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’""•–—

Просмотреть файл

@ -1,54 +1,47 @@
// <Snippet17>
using System;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json;
using System.Threading;
public class Example2
{
public static void Main2()
{
// Display the currency value.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Decimal value = 16039.47m;
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
Console.WriteLine("Currency Value: {0:C2}", value);
public static void Main2()
{
// Display the currency value.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Decimal value = 16039.47m;
Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.DisplayName}");
Console.WriteLine($"Currency Value: {value:C2}");
// Serialize the currency data.
BinaryFormatter bf = new BinaryFormatter();
FileStream fw = new FileStream("currency.dat", FileMode.Create);
CurrencyValue data = new CurrencyValue(value, CultureInfo.CurrentCulture.Name);
bf.Serialize(fw, data);
fw.Close();
Console.WriteLine();
// Serialize the currency data.
CurrencyValue data = new()
{
Amount = value,
CultureName = CultureInfo.CurrentCulture.Name
};
string serialized = JsonSerializer.Serialize(data);
Console.WriteLine();
// Change the current culture.
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
// Change the current culture.
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine($"Current Culture: {CultureInfo.CurrentCulture.DisplayName}");
// Deserialize the data.
FileStream fr = new FileStream("currency.dat", FileMode.Open);
CurrencyValue restoredData = (CurrencyValue) bf.Deserialize(fr);
fr.Close();
// Deserialize the data.
CurrencyValue restoredData = JsonSerializer.Deserialize<CurrencyValue>(serialized);
// Display the original value.
CultureInfo culture = CultureInfo.CreateSpecificCulture(restoredData.CultureName);
Console.WriteLine("Currency Value: {0}", restoredData.Amount.ToString("C2", culture));
}
// Display the round-tripped value.
CultureInfo culture = CultureInfo.CreateSpecificCulture(restoredData.CultureName);
Console.WriteLine($"Currency Value: {restoredData.Amount.ToString("C2", culture)}");
}
}
[Serializable] internal struct CurrencyValue
internal struct CurrencyValue
{
public CurrencyValue(Decimal amount, string name)
{
this.Amount = amount;
this.CultureName = name;
}
public Decimal Amount;
public string CultureName;
public decimal Amount { get; set; }
public string CultureName { get; set; }
}
// The example displays the following output:
// Current Culture: English (United States)
// Currency Value: $16,039.47

Просмотреть файл

@ -5,25 +5,26 @@ using System.Threading;
public class Example3
{
static DateTime[] dates = { new DateTime(2012, 10, 11, 7, 06, 0),
static DateTime[] dates = { new DateTime(2012, 10, 11, 7, 06, 0),
new DateTime(2012, 10, 11, 18, 19, 0) };
public static void Main3()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("hr-HR");
ShowDayInfo();
Console.WriteLine();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
ShowDayInfo();
}
public static void Main3()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("hr-HR");
ShowDayInfo();
Console.WriteLine();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
ShowDayInfo();
}
private static void ShowDayInfo()
{
Console.WriteLine("Date: {0:D}", dates[0]);
Console.WriteLine(" Sunrise: {0:T}", dates[0]);
Console.WriteLine(" Sunset: {0:T}", dates[1]);
}
private static void ShowDayInfo()
{
Console.WriteLine("Date: {0:D}", dates[0]);
Console.WriteLine(" Sunrise: {0:T}", dates[0]);
Console.WriteLine(" Sunset: {0:T}", dates[1]);
}
}
// The example displays the following output:
// Date: 11. listopada 2012.
// Sunrise: 7:06:00

Просмотреть файл

@ -6,47 +6,50 @@ using System.Threading;
public class Example4
{
public static void Main4()
{
// Persist two dates as strings.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
DateTime[] dates = { new DateTime(2013, 1, 9),
public static void Main4()
{
// Persist two dates as strings.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
DateTime[] dates = { new DateTime(2013, 1, 9),
new DateTime(2013, 8, 18) };
StreamWriter sw = new StreamWriter("dateData.dat");
sw.Write("{0:d}|{1:d}", dates[0], dates[1]);
sw.Close();
StreamWriter sw = new StreamWriter("dateData.dat");
sw.Write("{0:d}|{1:d}", dates[0], dates[1]);
sw.Close();
// Read the persisted data.
StreamReader sr = new StreamReader("dateData.dat");
string dateData = sr.ReadToEnd();
sr.Close();
string[] dateStrings = dateData.Split('|');
// Read the persisted data.
StreamReader sr = new StreamReader("dateData.dat");
string dateData = sr.ReadToEnd();
sr.Close();
string[] dateStrings = dateData.Split('|');
// Restore and display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings) {
DateTime restoredDate;
if (DateTime.TryParse(dateStr, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
Console.WriteLine();
// Restore and display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings)
{
DateTime restoredDate;
if (DateTime.TryParse(dateStr, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
Console.WriteLine();
// Restore and display the data using the conventions of the en-GB culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings) {
DateTime restoredDate;
if (DateTime.TryParse(dateStr, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
}
// Restore and display the data using the conventions of the en-GB culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings)
{
DateTime restoredDate;
if (DateTime.TryParse(dateStr, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
}
}
// The example displays the following output:
// Current Culture: English (United States)
// The date is Wednesday, January 09, 2013

Просмотреть файл

@ -6,50 +6,53 @@ using System.Threading;
public class Example5
{
public static void Main5()
{
// Persist two dates as strings.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
DateTime[] dates = { new DateTime(2013, 1, 9),
public static void Main5()
{
// Persist two dates as strings.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
DateTime[] dates = { new DateTime(2013, 1, 9),
new DateTime(2013, 8, 18) };
StreamWriter sw = new StreamWriter("dateData.dat");
sw.Write(String.Format(CultureInfo.InvariantCulture,
"{0:d}|{1:d}", dates[0], dates[1]));
sw.Close();
StreamWriter sw = new StreamWriter("dateData.dat");
sw.Write(String.Format(CultureInfo.InvariantCulture,
"{0:d}|{1:d}", dates[0], dates[1]));
sw.Close();
// Read the persisted data.
StreamReader sr = new StreamReader("dateData.dat");
string dateData = sr.ReadToEnd();
sr.Close();
string[] dateStrings = dateData.Split('|');
// Read the persisted data.
StreamReader sr = new StreamReader("dateData.dat");
string dateData = sr.ReadToEnd();
sr.Close();
string[] dateStrings = dateData.Split('|');
// Restore and display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings) {
DateTime restoredDate;
if (DateTime.TryParse(dateStr, CultureInfo.InvariantCulture,
DateTimeStyles.None, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
Console.WriteLine();
// Restore and display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings)
{
DateTime restoredDate;
if (DateTime.TryParse(dateStr, CultureInfo.InvariantCulture,
DateTimeStyles.None, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
Console.WriteLine();
// Restore and display the data using the conventions of the en-GB culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings) {
DateTime restoredDate;
if (DateTime.TryParse(dateStr, CultureInfo.InvariantCulture,
DateTimeStyles.None, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
}
// Restore and display the data using the conventions of the en-GB culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var dateStr in dateStrings)
{
DateTime restoredDate;
if (DateTime.TryParse(dateStr, CultureInfo.InvariantCulture,
DateTimeStyles.None, out restoredDate))
Console.WriteLine("The date is {0:D}", restoredDate);
else
Console.WriteLine("ERROR: Unable to parse {0}", dateStr);
}
}
}
// The example displays the following output:
// Current Culture: English (United States)
// The date is Wednesday, January 09, 2013

Просмотреть файл

@ -1,48 +1,34 @@
// <Snippet10>
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Example6
{
public static void Main6()
{
BinaryFormatter formatter = new BinaryFormatter();
public static void Main6()
{
DateTime dateOriginal = new DateTime(2023, 3, 30, 18, 0, 0);
dateOriginal = DateTime.SpecifyKind(dateOriginal, DateTimeKind.Local);
DateTime dateOriginal = new DateTime(2013, 3, 30, 18, 0, 0);
dateOriginal = DateTime.SpecifyKind(dateOriginal, DateTimeKind.Local);
// Serialize a date.
if (!File.Exists("DateInfo.dat"))
{
StreamWriter sw = new StreamWriter("DateInfo.dat");
sw.Write("{0:G}|{0:s}|{0:o}", dateOriginal);
sw.Close();
Console.WriteLine("Serialized dates to DateInfo.dat");
}
Console.WriteLine();
// Serialize a date.
if (! File.Exists("DateInfo.dat")) {
StreamWriter sw = new StreamWriter("DateInfo.dat");
sw.Write("{0:G}|{0:s}|{0:o}", dateOriginal);
sw.Close();
Console.WriteLine("Serialized dates to DateInfo.dat");
}
// Serialize the data as a binary value.
if (! File.Exists("DateInfo.bin")) {
FileStream fsIn = new FileStream("DateInfo.bin", FileMode.Create);
formatter.Serialize(fsIn, dateOriginal);
fsIn.Close();
Console.WriteLine("Serialized date to DateInfo.bin");
}
Console.WriteLine();
// Restore the date from string values.
StreamReader sr = new StreamReader("DateInfo.dat");
string datesToSplit = sr.ReadToEnd();
string[] dateStrings = datesToSplit.Split('|');
foreach (var dateStr in dateStrings) {
DateTime newDate = DateTime.Parse(dateStr);
Console.WriteLine("'{0}' --> {1} {2}",
dateStr, newDate, newDate.Kind);
}
Console.WriteLine();
// Restore the date from binary data.
FileStream fsOut = new FileStream("DateInfo.bin", FileMode.Open);
DateTime restoredDate = (DateTime) formatter.Deserialize(fsOut);
Console.WriteLine("{0} {1}", restoredDate, restoredDate.Kind);
}
// Restore the date from string values.
StreamReader sr = new StreamReader("DateInfo.dat");
string datesToSplit = sr.ReadToEnd();
string[] dateStrings = datesToSplit.Split('|');
foreach (var dateStr in dateStrings)
{
DateTime newDate = DateTime.Parse(dateStr);
Console.WriteLine("'{0}' --> {1} {2}",
dateStr, newDate, newDate.Kind);
}
}
}
// </Snippet10>

Просмотреть файл

@ -3,16 +3,17 @@ using System;
public class Example7
{
public static void Main7()
{
DateTime date1 = DateTime.SpecifyKind(new DateTime(2013, 3, 9, 10, 30, 0),
DateTimeKind.Local);
TimeSpan interval = new TimeSpan(48, 0, 0);
DateTime date2 = date1 + interval;
Console.WriteLine("{0:g} + {1:N1} hours = {2:g}",
date1, interval.TotalHours, date2);
}
public static void Main7()
{
DateTime date1 = DateTime.SpecifyKind(new DateTime(2013, 3, 9, 10, 30, 0),
DateTimeKind.Local);
TimeSpan interval = new TimeSpan(48, 0, 0);
DateTime date2 = date1 + interval;
Console.WriteLine("{0:g} + {1:N1} hours = {2:g}",
date1, interval.TotalHours, date2);
}
}
// The example displays the following output:
// 3/9/2013 10:30 AM + 48.0 hours = 3/11/2013 10:30 AM
// </Snippet8>

Просмотреть файл

@ -3,19 +3,20 @@ using System;
public class Example8
{
public static void Main8()
{
TimeZoneInfo pst = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime date1 = DateTime.SpecifyKind(new DateTime(2013, 3, 9, 10, 30, 0),
DateTimeKind.Local);
DateTime utc1 = date1.ToUniversalTime();
TimeSpan interval = new TimeSpan(48, 0, 0);
DateTime utc2 = utc1 + interval;
DateTime date2 = TimeZoneInfo.ConvertTimeFromUtc(utc2, pst);
Console.WriteLine("{0:g} + {1:N1} hours = {2:g}",
date1, interval.TotalHours, date2);
}
public static void Main8()
{
TimeZoneInfo pst = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime date1 = DateTime.SpecifyKind(new DateTime(2013, 3, 9, 10, 30, 0),
DateTimeKind.Local);
DateTime utc1 = date1.ToUniversalTime();
TimeSpan interval = new TimeSpan(48, 0, 0);
DateTime utc2 = utc1 + interval;
DateTime date2 = TimeZoneInfo.ConvertTimeFromUtc(utc2, pst);
Console.WriteLine("{0:g} + {1:N1} hours = {2:g}",
date1, interval.TotalHours, date2);
}
}
// The example displays the following output:
// 3/9/2013 10:30 AM + 48.0 hours = 3/11/2013 11:30 AM
// </Snippet9>

Просмотреть файл

@ -1,58 +1,41 @@
// <Snippet11>
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
public class Example9
{
public static void Main9()
{
BinaryFormatter formatter = new BinaryFormatter();
public static void Main9()
{
// Serialize a date.
DateTime dateOriginal = new DateTime(2023, 3, 30, 18, 0, 0);
dateOriginal = DateTime.SpecifyKind(dateOriginal, DateTimeKind.Local);
// Serialize a date.
DateTime dateOriginal = new DateTime(2013, 3, 30, 18, 0, 0);
dateOriginal = DateTime.SpecifyKind(dateOriginal, DateTimeKind.Local);
// Serialize the date in string form.
if (!File.Exists("DateInfo2.dat"))
{
StreamWriter sw = new StreamWriter("DateInfo2.dat");
sw.Write("{0:o}|{1:r}|{1:u}", dateOriginal,
dateOriginal.ToUniversalTime());
sw.Close();
}
// Serialize the date in string form.
if (! File.Exists("DateInfo2.dat")) {
StreamWriter sw = new StreamWriter("DateInfo2.dat");
sw.Write("{0:o}|{1:r}|{1:u}", dateOriginal,
dateOriginal.ToUniversalTime());
sw.Close();
Console.WriteLine("Serialized dates to DateInfo.dat");
}
// Serialize the date as a binary value.
if (! File.Exists("DateInfo2.bin")) {
FileStream fsIn = new FileStream("DateInfo2.bin", FileMode.Create);
formatter.Serialize(fsIn, dateOriginal.ToUniversalTime());
fsIn.Close();
Console.WriteLine("Serialized date to DateInfo.bin");
}
Console.WriteLine();
// Restore the date from string values.
StreamReader sr = new StreamReader("DateInfo2.dat");
string datesToSplit = sr.ReadToEnd();
string[] dateStrings = datesToSplit.Split('|');
for (int ctr = 0; ctr < dateStrings.Length; ctr++) {
DateTime newDate = DateTime.Parse(dateStrings[ctr]);
if (ctr == 1) {
Console.WriteLine("'{0}' --> {1} {2}",
dateStrings[ctr], newDate, newDate.Kind);
}
else {
DateTime newLocalDate = newDate.ToLocalTime();
Console.WriteLine("'{0}' --> {1} {2}",
dateStrings[ctr], newLocalDate, newLocalDate.Kind);
}
}
Console.WriteLine();
// Restore the date from binary data.
FileStream fsOut = new FileStream("DateInfo2.bin", FileMode.Open);
DateTime restoredDate = (DateTime) formatter.Deserialize(fsOut);
restoredDate = restoredDate.ToLocalTime();
Console.WriteLine("{0} {1}", restoredDate, restoredDate.Kind);
}
// Restore the date from string values.
StreamReader sr = new StreamReader("DateInfo2.dat");
string datesToSplit = sr.ReadToEnd();
string[] dateStrings = datesToSplit.Split('|');
for (int ctr = 0; ctr < dateStrings.Length; ctr++)
{
DateTime newDate = DateTime.Parse(dateStrings[ctr]);
if (ctr == 1)
{
Console.WriteLine($"'{dateStrings[ctr]}' --> {newDate} {newDate.Kind}");
}
else
{
DateTime newLocalDate = newDate.ToLocalTime();
Console.WriteLine($"'{dateStrings[ctr]}' --> {newLocalDate} {newLocalDate.Kind}");
}
}
}
}
// </Snippet11>

Просмотреть файл

@ -5,23 +5,24 @@ using System.Threading;
public class Example10
{
public static void Main10()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");
string uri = @"file:\\c:\users\username\Documents\bio.txt";
if (! AccessesFileSystem(uri))
// Permit access to resource specified by URI
Console.WriteLine("Access is allowed.");
else
// Prohibit access.
Console.WriteLine("Access is not allowed.");
}
public static void Main10()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");
string uri = @"file:\\c:\users\username\Documents\bio.txt";
if (!AccessesFileSystem(uri))
// Permit access to resource specified by URI
Console.WriteLine("Access is allowed.");
else
// Prohibit access.
Console.WriteLine("Access is not allowed.");
}
private static bool AccessesFileSystem(string uri)
{
return uri.StartsWith("FILE", true, CultureInfo.CurrentCulture);
}
private static bool AccessesFileSystem(string uri)
{
return uri.StartsWith("FILE", true, CultureInfo.CurrentCulture);
}
}
// The example displays the following output:
// Access is allowed.
// </Snippet12>

Просмотреть файл

@ -5,23 +5,24 @@ using System.Threading;
public class Example11
{
public static void Main11()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");
string uri = @"file:\\c:\users\username\Documents\bio.txt";
if (! AccessesFileSystem(uri))
// Permit access to resource specified by URI
Console.WriteLine("Access is allowed.");
else
// Prohibit access.
Console.WriteLine("Access is not allowed.");
}
public static void Main11()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("tr-TR");
string uri = @"file:\\c:\users\username\Documents\bio.txt";
if (!AccessesFileSystem(uri))
// Permit access to resource specified by URI
Console.WriteLine("Access is allowed.");
else
// Prohibit access.
Console.WriteLine("Access is not allowed.");
}
private static bool AccessesFileSystem(string uri)
{
return uri.StartsWith("FILE", StringComparison.OrdinalIgnoreCase);
}
private static bool AccessesFileSystem(string uri)
{
return uri.StartsWith("FILE", StringComparison.OrdinalIgnoreCase);
}
}
// The example displays the following output:
// Access is not allowed.
// </Snippet13>

Просмотреть файл

@ -14,6 +14,7 @@ public class Example12
return date.DayOfWeek.ToString("G");
}
}
// The example displays the following output:
// 7/1/2013 is a Monday.
// </Snippet19>

Просмотреть файл

@ -1,51 +1,51 @@
// <Snippet20>
using System;
using System.Globalization;
using System.Threading;
public class Example13
{
public static void Main13()
{
// Set the current culture to French (France).
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
public static void Main13()
{
// Set the current culture to French (France).
CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
DateTime midYear = new DateTime(2013, 7, 1);
Console.WriteLine("{0:d} is a {1}.", midYear, DateUtilities.GetDayName(midYear));
Console.WriteLine("{0:d} is a {1}.", midYear, DateUtilities.GetDayName((int) midYear.DayOfWeek));
Console.WriteLine("{0:d} is in {1}.", midYear, DateUtilities.GetMonthName(midYear));
Console.WriteLine("{0:d} is in {1}.", midYear, DateUtilities.GetMonthName(midYear.Month));
}
DateTime midYear = new DateTime(2013, 7, 1);
Console.WriteLine("{0:d} is a {1}.", midYear, DateUtilities.GetDayName(midYear));
Console.WriteLine("{0:d} is a {1}.", midYear, DateUtilities.GetDayName((int)midYear.DayOfWeek));
Console.WriteLine("{0:d} is in {1}.", midYear, DateUtilities.GetMonthName(midYear));
Console.WriteLine("{0:d} is in {1}.", midYear, DateUtilities.GetMonthName(midYear.Month));
}
}
public static class DateUtilities
{
public static string GetDayName(int dayOfWeek)
{
if (dayOfWeek < 0 | dayOfWeek > DateTimeFormatInfo.CurrentInfo.DayNames.Length)
return String.Empty;
else
return DateTimeFormatInfo.CurrentInfo.DayNames[dayOfWeek];
}
public static string GetDayName(int dayOfWeek)
{
if (dayOfWeek < 0 | dayOfWeek > DateTimeFormatInfo.CurrentInfo.DayNames.Length)
return String.Empty;
else
return DateTimeFormatInfo.CurrentInfo.DayNames[dayOfWeek];
}
public static string GetDayName(DateTime date)
{
return date.ToString("dddd");
}
public static string GetDayName(DateTime date)
{
return date.ToString("dddd");
}
public static string GetMonthName(int month)
{
if (month < 1 | month > DateTimeFormatInfo.CurrentInfo.MonthNames.Length - 1)
return String.Empty;
else
return DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1];
}
public static string GetMonthName(int month)
{
if (month < 1 | month > DateTimeFormatInfo.CurrentInfo.MonthNames.Length - 1)
return String.Empty;
else
return DateTimeFormatInfo.CurrentInfo.MonthNames[month - 1];
}
public static string GetMonthName(DateTime date)
{
return date.ToString("MMMM");
}
public static string GetMonthName(DateTime date)
{
return date.ToString("MMMM");
}
}
// The example displays the following output:
// 01/07/2013 is a lundi.
// 01/07/2013 is a lundi.

Просмотреть файл

@ -5,41 +5,42 @@ using System.Threading;
public class Example14
{
public static void Main14()
{
DateTime dateForMonth = new DateTime(2013, 1, 1);
double[] temperatures = { 3.4, 3.5, 7.6, 10.4, 14.5, 17.2,
public static void Main14()
{
DateTime dateForMonth = new DateTime(2013, 1, 1);
double[] temperatures = { 3.4, 3.5, 7.6, 10.4, 14.5, 17.2,
19.9, 18.2, 15.9, 11.3, 6.9, 5.3 };
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
// Build the format string dynamically so we allocate enough space for the month name.
string fmtString = "{0,-" + GetLongestMonthNameLength().ToString() + ":MMMM} {1,4}";
for (int ctr = 0; ctr < temperatures.Length; ctr++)
Console.WriteLine(fmtString,
dateForMonth.AddMonths(ctr),
temperatures[ctr]);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
// Build the format string dynamically so we allocate enough space for the month name.
string fmtString = "{0,-" + GetLongestMonthNameLength().ToString() + ":MMMM} {1,4}";
for (int ctr = 0; ctr < temperatures.Length; ctr++)
Console.WriteLine(fmtString,
dateForMonth.AddMonths(ctr),
temperatures[ctr]);
Console.WriteLine();
Console.WriteLine();
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
fmtString = "{0,-" + GetLongestMonthNameLength().ToString() + ":MMMM} {1,4}";
for (int ctr = 0; ctr < temperatures.Length; ctr++)
Console.WriteLine(fmtString,
dateForMonth.AddMonths(ctr),
temperatures[ctr]);
}
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName);
fmtString = "{0,-" + GetLongestMonthNameLength().ToString() + ":MMMM} {1,4}";
for (int ctr = 0; ctr < temperatures.Length; ctr++)
Console.WriteLine(fmtString,
dateForMonth.AddMonths(ctr),
temperatures[ctr]);
}
private static int GetLongestMonthNameLength()
{
int length = 0;
foreach (var nameOfMonth in DateTimeFormatInfo.CurrentInfo.MonthNames)
if (nameOfMonth.Length > length) length = nameOfMonth.Length;
private static int GetLongestMonthNameLength()
{
int length = 0;
foreach (var nameOfMonth in DateTimeFormatInfo.CurrentInfo.MonthNames)
if (nameOfMonth.Length > length) length = nameOfMonth.Length;
return length;
}
return length;
}
}
// The example displays the following output:
// Current Culture: French (France)
// janvier 3,4

Просмотреть файл

@ -6,67 +6,70 @@ using System.Threading;
public class Example15
{
public static void Main15()
{
// Create ten random doubles.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
double[] numbers = GetRandomNumbers(10);
DisplayRandomNumbers(numbers);
public static void Main15()
{
// Create ten random doubles.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
double[] numbers = GetRandomNumbers(10);
DisplayRandomNumbers(numbers);
// Persist the numbers as strings.
StreamWriter sw = new StreamWriter("randoms.dat");
for (int ctr = 0; ctr < numbers.Length; ctr++)
sw.Write("{0:R}{1}", numbers[ctr], ctr < numbers.Length - 1 ? "|" : "");
// Persist the numbers as strings.
StreamWriter sw = new StreamWriter("randoms.dat");
for (int ctr = 0; ctr < numbers.Length; ctr++)
sw.Write("{0:R}{1}", numbers[ctr], ctr < numbers.Length - 1 ? "|" : "");
sw.Close();
sw.Close();
// Read the persisted data.
StreamReader sr = new StreamReader("randoms.dat");
string numericData = sr.ReadToEnd();
sr.Close();
string[] numberStrings = numericData.Split('|');
// Read the persisted data.
StreamReader sr = new StreamReader("randoms.dat");
string numericData = sr.ReadToEnd();
sr.Close();
string[] numberStrings = numericData.Split('|');
// Restore and display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var numberStr in numberStrings) {
double restoredNumber;
if (Double.TryParse(numberStr, out restoredNumber))
Console.WriteLine(restoredNumber.ToString("R"));
else
Console.WriteLine("ERROR: Unable to parse '{0}'", numberStr);
}
Console.WriteLine();
// Restore and display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var numberStr in numberStrings)
{
double restoredNumber;
if (Double.TryParse(numberStr, out restoredNumber))
Console.WriteLine(restoredNumber.ToString("R"));
else
Console.WriteLine("ERROR: Unable to parse '{0}'", numberStr);
}
Console.WriteLine();
// Restore and display the data using the conventions of the fr-FR culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var numberStr in numberStrings) {
double restoredNumber;
if (Double.TryParse(numberStr, out restoredNumber))
Console.WriteLine(restoredNumber.ToString("R"));
else
Console.WriteLine("ERROR: Unable to parse '{0}'", numberStr);
}
}
// Restore and display the data using the conventions of the fr-FR culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
foreach (var numberStr in numberStrings)
{
double restoredNumber;
if (Double.TryParse(numberStr, out restoredNumber))
Console.WriteLine(restoredNumber.ToString("R"));
else
Console.WriteLine("ERROR: Unable to parse '{0}'", numberStr);
}
}
private static double[] GetRandomNumbers(int n)
{
Random rnd = new Random();
double[] numbers = new double[n];
for (int ctr = 0; ctr < n; ctr++)
numbers[ctr] = rnd.NextDouble() * 1000;
return numbers;
}
private static double[] GetRandomNumbers(int n)
{
Random rnd = new Random();
double[] numbers = new double[n];
for (int ctr = 0; ctr < n; ctr++)
numbers[ctr] = rnd.NextDouble() * 1000;
return numbers;
}
private static void DisplayRandomNumbers(double[] numbers)
{
for (int ctr = 0; ctr < numbers.Length; ctr++)
Console.WriteLine(numbers[ctr].ToString("R"));
Console.WriteLine();
}
private static void DisplayRandomNumbers(double[] numbers)
{
for (int ctr = 0; ctr < numbers.Length; ctr++)
Console.WriteLine(numbers[ctr].ToString("R"));
Console.WriteLine();
}
}
// The example displays output like the following:
// 487.0313743534644
// 674.12000879371533

Просмотреть файл

@ -1,91 +0,0 @@
// <Snippet7>
using System;
using System.Globalization;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
public class Example16
{
public static void Main16()
{
// Create ten random doubles.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
double[] numbers = GetRandomNumbers(10);
DisplayRandomNumbers(numbers);
// Serialize the array.
FileStream fsIn = new FileStream("randoms.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(fsIn, numbers);
fsIn.Close();
// Read the persisted data.
FileStream fsOut = new FileStream("randoms.dat", FileMode.Open);
double[] numbers1 = (Double[]) formatter.Deserialize(fsOut);
fsOut.Close();
// Display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
DisplayRandomNumbers(numbers1);
// Display the data using the conventions of the fr-FR culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR");
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName);
DisplayRandomNumbers(numbers1);
}
private static double[] GetRandomNumbers(int n)
{
Random rnd = new Random();
double[] numbers = new double[n];
for (int ctr = 0; ctr < n; ctr++)
numbers[ctr] = rnd.NextDouble() * 1000;
return numbers;
}
private static void DisplayRandomNumbers(double[] numbers)
{
for (int ctr = 0; ctr < numbers.Length; ctr++)
Console.WriteLine(numbers[ctr].ToString("R"));
Console.WriteLine();
}
}
// The example displays output like the following:
// 932.10070623648392
// 96.868112262742642
// 857.111520067375
// 771.37727233179726
// 262.65733840999064
// 387.00796914613244
// 557.49389788019187
// 83.79498919648816
// 957.31006048494487
// 996.54487892824454
//
// Current Culture: English (United States)
// 932.10070623648392
// 96.868112262742642
// 857.111520067375
// 771.37727233179726
// 262.65733840999064
// 387.00796914613244
// 557.49389788019187
// 83.79498919648816
// 957.31006048494487
// 996.54487892824454
//
// Current Culture: French (France)
// 932,10070623648392
// 96,868112262742642
// 857,111520067375
// 771,37727233179726
// 262,65733840999064
// 387,00796914613244
// 557,49389788019187
// 83,79498919648816
// 957,31006048494487
// 996,54487892824454
// </Snippet7>

Просмотреть файл

@ -0,0 +1 @@
Example9.Main9();

Просмотреть файл

@ -5,14 +5,15 @@ using System.Threading;
public class Example17
{
public static void Main17()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pl-PL");
string composite = "\u0041\u0300";
Console.WriteLine("Comparing using Char: {0}", composite.IndexOf('\u00C0'));
Console.WriteLine("Comparing using String: {0}", composite.IndexOf("\u00C0"));
}
public static void Main17()
{
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("pl-PL");
string composite = "\u0041\u0300";
Console.WriteLine("Comparing using Char: {0}", composite.IndexOf('\u00C0'));
Console.WriteLine("Comparing using String: {0}", composite.IndexOf("\u00C0"));
}
}
// The example displays the following output:
// Comparing using Char: -1
// Comparing using String: 0

Просмотреть файл

@ -5,27 +5,28 @@ using System.Threading;
public class Example18
{
public static void Main18()
{
string[] values = { "able", "ångström", "apple", "Æble",
public static void Main18()
{
string[] values = { "able", "ångström", "apple", "Æble",
"Windows", "Visual Studio" };
// Change thread to en-US.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// Sort the array and copy it to a new array to preserve the order.
Array.Sort(values);
string[] enValues = (String[]) values.Clone();
// Change thread to en-US.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// Sort the array and copy it to a new array to preserve the order.
Array.Sort(values);
string[] enValues = (String[])values.Clone();
// Change culture to Swedish (Sweden).
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("sv-SE");
Array.Sort(values);
string[] svValues = (String[]) values.Clone();
// Change culture to Swedish (Sweden).
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("sv-SE");
Array.Sort(values);
string[] svValues = (String[])values.Clone();
// Compare the sorted arrays.
Console.WriteLine("{0,-8} {1,-15} {2,-15}\n", "Position", "en-US", "sv-SE");
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
Console.WriteLine("{0,-8} {1,-15} {2,-15}", ctr, enValues[ctr], svValues[ctr]);
}
// Compare the sorted arrays.
Console.WriteLine("{0,-8} {1,-15} {2,-15}\n", "Position", "en-US", "sv-SE");
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
Console.WriteLine("{0,-8} {1,-15} {2,-15}", ctr, enValues[ctr], svValues[ctr]);
}
}
// The example displays the following output:
// Position en-US sv-SE
//

Просмотреть файл

@ -6,40 +6,41 @@ using System.Threading;
public class SortKeyComparer : IComparer<String>
{
public int Compare(string str1, string str2)
{
SortKey sk1, sk2;
sk1 = CultureInfo.CurrentCulture.CompareInfo.GetSortKey(str1);
sk2 = CultureInfo.CurrentCulture.CompareInfo.GetSortKey(str2);
return SortKey.Compare(sk1, sk2);
}
public int Compare(string str1, string str2)
{
SortKey sk1, sk2;
sk1 = CultureInfo.CurrentCulture.CompareInfo.GetSortKey(str1);
sk2 = CultureInfo.CurrentCulture.CompareInfo.GetSortKey(str2);
return SortKey.Compare(sk1, sk2);
}
}
public class Example19
{
public static void Main19()
{
string[] values = { "able", "ångström", "apple", "Æble",
public static void Main19()
{
string[] values = { "able", "ångström", "apple", "Æble",
"Windows", "Visual Studio" };
SortKeyComparer comparer = new SortKeyComparer();
SortKeyComparer comparer = new SortKeyComparer();
// Change thread to en-US.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// Sort the array and copy it to a new array to preserve the order.
Array.Sort(values, comparer);
string[] enValues = (String[]) values.Clone();
// Change thread to en-US.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");
// Sort the array and copy it to a new array to preserve the order.
Array.Sort(values, comparer);
string[] enValues = (String[])values.Clone();
// Change culture to Swedish (Sweden).
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("sv-SE");
Array.Sort(values, comparer);
string[] svValues = (String[]) values.Clone();
// Change culture to Swedish (Sweden).
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("sv-SE");
Array.Sort(values, comparer);
string[] svValues = (String[])values.Clone();
// Compare the sorted arrays.
Console.WriteLine("{0,-8} {1,-15} {2,-15}\n", "Position", "en-US", "sv-SE");
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
Console.WriteLine("{0,-8} {1,-15} {2,-15}", ctr, enValues[ctr], svValues[ctr]);
}
// Compare the sorted arrays.
Console.WriteLine("{0,-8} {1,-15} {2,-15}\n", "Position", "en-US", "sv-SE");
for (int ctr = 0; ctr <= values.GetUpperBound(0); ctr++)
Console.WriteLine("{0,-8} {1,-15} {2,-15}", ctr, enValues[ctr], svValues[ctr]);
}
}
// The example displays the following output:
// Position en-US sv-SE
//

Просмотреть файл

@ -0,0 +1,5 @@
Module Program
Public Sub Main()
Example2.Main2()
End Sub
End Module

Просмотреть файл

@ -6,7 +6,7 @@ Imports System.IO
Imports System.Text
Module Example
Public Sub Main()
Public Sub CodePages()
' Represent Greek uppercase characters in code page 737.
Dim greekChars() As Char = {"Α"c, "Β"c, "Γ"c, "Δ"c, "Ε"c, "Ζ"c, "Η"c, "Θ"c,
"Ι"c, "Κ"c, "Λ"c, "Μ"c, "Ν"c, "Ξ"c, "Ο"c, "Π"c,

Просмотреть файл

@ -1,20 +1,11 @@
' Visual Basic .NET Document
Option Strict On
' <Snippet17>
' <Snippet17>
Imports System.Globalization
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Text.Json
Imports System.Threading
<Serializable> Friend Structure CurrencyValue
Public Sub New(amount As Decimal, name As String)
Me.Amount = amount
Me.CultureName = name
End Sub
Public Amount As Decimal
Public CultureName As String
Friend Structure CurrencyValue
Public Property Amount As Decimal
Public Property CultureName As String
End Structure
Module Example2
@ -26,11 +17,12 @@ Module Example2
Console.WriteLine("Currency Value: {0:C2}", value)
' Serialize the currency data.
Dim bf As New BinaryFormatter()
Dim fw As New FileStream("currency.dat", FileMode.Create)
Dim data As New CurrencyValue(value, CultureInfo.CurrentCulture.Name)
bf.Serialize(fw, data)
fw.Close()
Dim data As New CurrencyValue With {
.Amount = value,
.CultureName = CultureInfo.CurrentCulture.Name
}
Dim serialized As String = JsonSerializer.Serialize(data)
Console.WriteLine()
' Change the current culture.
@ -38,11 +30,9 @@ Module Example2
Console.WriteLine("Current Culture: {0}", CultureInfo.CurrentCulture.DisplayName)
' Deserialize the data.
Dim fr As New FileStream("currency.dat", FileMode.Open)
Dim restoredData As CurrencyValue = CType(bf.Deserialize(fr), CurrencyValue)
fr.Close()
Dim restoredData As CurrencyValue = JsonSerializer.Deserialize(Of CurrencyValue)(serialized)
' Display the original value.
' Display the round-tripped value.
Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(restoredData.CultureName)
Console.WriteLine("Currency Value: {0}", restoredData.Amount.ToString("C2", culture))
End Sub

Просмотреть файл

@ -3,30 +3,18 @@ Option Strict On
' <Snippet10>
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Module Example6
Public Sub Main6()
Dim formatter As New BinaryFormatter()
' Serialize a date.
Dim dateOriginal As Date = #03/30/2013 6:00PM#
Dim dateOriginal As Date = #03/30/2023 6:00PM#
dateOriginal = DateTime.SpecifyKind(dateOriginal, DateTimeKind.Local)
' Serialize the date in string form.
If Not File.Exists("DateInfo.dat") Then
Dim sw As New StreamWriter("DateInfo.dat")
sw.Write("{0:G}|{0:s}|{0:o}", dateOriginal)
sw.Close()
Console.WriteLine("Serialized dates to DateInfo.dat")
End If
' Serialize the date as a binary value.
If Not File.Exists("DateInfo.bin") Then
Dim fsIn As New FileStream("DateInfo.bin", FileMode.Create)
formatter.Serialize(fsIn, dateOriginal)
fsIn.Close()
Console.WriteLine("Serialized date to DateInfo.bin")
End If
Console.WriteLine()
' Restore the date from string values.
Dim sr As New StreamReader("DateInfo.dat")
@ -37,12 +25,6 @@ Module Example6
Console.WriteLine("'{0}' --> {1} {2}",
dateStr, newDate, newDate.Kind)
Next
Console.WriteLine()
' Restore the date from binary data.
Dim fsOut As New FileStream("DateInfo.bin", FileMode.Open)
Dim restoredDate As Date = DirectCast(formatter.Deserialize(fsOut), DateTime)
Console.WriteLine("{0} {1}", restoredDate, restoredDate.Kind)
End Sub
End Module
' </Snippet10>

Просмотреть файл

@ -3,14 +3,11 @@ Option Strict On
' <Snippet11>
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Module Example9
Public Sub Main9()
Dim formatter As New BinaryFormatter()
' Serialize a date.
Dim dateOriginal As Date = #03/30/2013 6:00PM#
Dim dateOriginal As Date = #03/30/2023 6:00PM#
dateOriginal = DateTime.SpecifyKind(dateOriginal, DateTimeKind.Local)
' Serialize the date in string form.
@ -19,16 +16,7 @@ Module Example9
sw.Write("{0:o}|{1:r}|{1:u}", dateOriginal,
dateOriginal.ToUniversalTime())
sw.Close()
Console.WriteLine("Serialized dates to DateInfo.dat")
End If
' Serialize the date as a binary value.
If Not File.Exists("DateInfo2.bin") Then
Dim fsIn As New FileStream("DateInfo2.bin", FileMode.Create)
formatter.Serialize(fsIn, dateOriginal.ToUniversalTime())
fsIn.Close()
Console.WriteLine("Serialized date to DateInfo.bin")
End If
Console.WriteLine()
' Restore the date from string values.
Dim sr As New StreamReader("DateInfo2.dat")
@ -45,13 +33,6 @@ Module Example9
dateStrings(ctr), newLocalDate, newLocalDate.Kind)
End If
Next
Console.WriteLine()
' Restore the date from binary data.
Dim fsOut As New FileStream("DateInfo2.bin", FileMode.Open)
Dim restoredDate As Date = DirectCast(formatter.Deserialize(fsOut), DateTime)
restoredDate = restoredDate.ToLocalTime()
Console.WriteLine("{0} {1}", restoredDate, restoredDate.Kind)
End Sub
End Module
' </Snippet11>

Просмотреть файл

@ -1,91 +0,0 @@
' Visual Basic .NET Document
Option Strict On
' <Snippet7>
Imports System.Globalization
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Threading
Module Example16
Public Sub Main16()
' Create ten random doubles.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US")
Dim numbers() As Double = GetRandomNumbers(10)
DisplayRandomNumbers(numbers)
' Serialize the array.
Dim fsIn As New FileStream("randoms.dat", FileMode.Create)
Dim formatter As New BinaryFormatter()
formatter.Serialize(fsIn, numbers)
fsIn.Close()
' Read the persisted data.
Dim fsOut As New FileStream("randoms.dat", FileMode.Open)
Dim numbers1() As Double = DirectCast(formatter.Deserialize(fsOut), Double())
fsOut.Close()
' Display the data using the conventions of the en-US culture.
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName)
DisplayRandomNumbers(numbers1)
' Display the data using the conventions of the fr-FR culture.
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("fr-FR")
Console.WriteLine("Current Culture: {0}",
Thread.CurrentThread.CurrentCulture.DisplayName)
DisplayRandomNumbers(numbers1)
End Sub
Private Function GetRandomNumbers(n As Integer) As Double()
Dim rnd As New Random()
Dim numbers(n - 1) As Double
For ctr As Integer = 0 To n - 1
numbers(ctr) = rnd.NextDouble * 1000
Next
Return numbers
End Function
Private Sub DisplayRandomNumbers(numbers As Double())
For ctr As Integer = 0 To numbers.Length - 1
Console.WriteLine(numbers(ctr).ToString("R"))
Next
Console.WriteLine()
End Sub
End Module
' The example displays output like the following:
' 932.10070623648392
' 96.868112262742642
' 857.111520067375
' 771.37727233179726
' 262.65733840999064
' 387.00796914613244
' 557.49389788019187
' 83.79498919648816
' 957.31006048494487
' 996.54487892824454
'
' Current Culture: English (United States)
' 932.10070623648392
' 96.868112262742642
' 857.111520067375
' 771.37727233179726
' 262.65733840999064
' 387.00796914613244
' 557.49389788019187
' 83.79498919648816
' 957.31006048494487
' 996.54487892824454
'
' Current Culture: French (France)
' 932,10070623648392
' 96,868112262742642
' 857,111520067375
' 771,37727233179726
' 262,65733840999064
' 387,00796914613244
' 557,49389788019187
' 83,79498919648816
' 957,31006048494487
' 996,54487892824454
' </Snippet7>