如何:获取和设置应用程序范围的属性

更新:2007 年 11 月

此示例演示了如何使用 Properties 来获取和设置应用程序范围的属性。

示例

Application 为可以在整个 AppDomainProperties 共享的属性公开数据存储区。

该属性数据存储区是一个可按如下方式使用的键/值对字典:

// Set an application-scope property
Application.Current.Properties["MyApplicationScopeProperty"] = "myApplicationScopePropertyValue";
// Get an application-scope property
// NOTE: Need to convert since Application.Properties is a dictionary of System.Object
string myApplicationScopeProperty = (string)Application.Current.Properties["MyApplicationScopeProperty"];

当使用 Properties 时有两个注意事项。首先,字典的键 是一个对象,因此设置和获取属性值时需要准确使用相同的对象实例(请注意:使用字符串键时该键区分大小写)。其次,字典的值 是一个对象,因此获取属性值时需要将该值转换成需要的类型。

因为字典的值是一个对象,因此可以像使用简单类型一样轻松使用自定义类型,如下所示:

// Set an application-scope property with a custom type
CustomType customType = new CustomType();
Application.Current.Properties["CustomType"] = customType;
// Get an application-scope property
// NOTE: Need to convert since Application.Properties is a dictionary of System.Object
CustomType customType = (CustomType)Application.Current.Properties["CustomType"];

请参见

参考

IDictionary