C# 将TimeZoneInfo.DisplayName转换为TimeZoneInfo.Id

C# 将TimeZoneInfo.DisplayName转换为TimeZoneInfo.Id,c#,windows,timezone,C#,Windows,Timezone,我需要将TimeZoneInfo.DisplayName转换为TimeZoneInfo.Id 我从一个组合框中获取DisplayName,该组合框由取自TimeZoneInfo.GetSystemTimeZones()的名称填充而成 var timeZone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(t => t.DisplayName == displayName).Id; 不需要转换,也不建议转换 TimeZoneInfo.

我需要将
TimeZoneInfo.DisplayName
转换为
TimeZoneInfo.Id

我从一个组合框中获取DisplayName,该组合框由取自
TimeZoneInfo.GetSystemTimeZones()的名称填充而成

var timeZone = TimeZoneInfo.GetSystemTimeZones().FirstOrDefault(t => t.DisplayName == displayName).Id;

不需要转换,也不建议转换

TimeZoneInfo.GetSystemTimeZones()
返回
TimeZoneInfo
对象的集合,而不是字符串

当您将该集合分配给组合框时(根据我们在中的讨论假设为
Windows.Forms.ComboBox
),组合框将显示每个
TimeZoneInfo
对象的
DisplayName
属性,但保留原始对象

您真正需要的是获取组合框所选择的
TimeZoneInfo
对象的
Id

换句话说,假设您像这样填充组合框:

this.cboTimeZone.DataSource = TimeZoneInfo.GetSystemTimeZones();
TimeZoneInfo tzi = (TimeZoneInfo) this.cboTimeZone.SelectedItem;
string id = tzi?.Id;
然后您可以获得所选项目的
Id
,如下所示:

this.cboTimeZone.DataSource = TimeZoneInfo.GetSystemTimeZones();
TimeZoneInfo tzi = (TimeZoneInfo) this.cboTimeZone.SelectedItem;
string id = tzi?.Id;
或者作为一个单独的声明:

string id = ((TimeZoneInfo) this.cboTimeZone.SelectedItem)?.Id;

请注意,我使用了
?。
运算符,因此如果没有选择任何项,则生成的字符串将为
null
,而不是抛出
NullReferenceException

它需要是TimeZoneInfo.Id的一种类型(不是var)@BartDivanov var在这里表示
字符串。
TimeZoneInfo.Id
的类型为字符串。您可以编写
string
而不是
var
TimeZoneInfo.GetSystemTimeZones()
返回一个iterable对象。您可以在此上使用Linq扩展方法。另外-请记住,
Id
属性的字符串用于标识系统的时区。无论Windows的语言设置如何,这些字符串都是相同的。但是,
DisplayName
字符串旨在使人可读,并将更改以匹配Windows语言设置。