如何在“设置”中拥有自己的类型。
我成功地将它们放在设置表中,但问题是我无法设置默认值。
问题是我在 app.config 中看不到设置。
最佳答案
如果我正确解释了您的问题,您有一个自定义类型,我们称之为 CustomSetting
,并且您在该类型的 Settings.settings
文件中有一个设置,并使用 app.config
或 Visual Studio 的设置 UI 为该设置指定默认值。
如果这是你想要做的,你需要为你的类型提供一个可以从字符串转换的 TypeConverter
,如下所示:
[TypeConverter(typeof(CustomSettingConverter))]
public class CustomSetting
{
public string Foo { get; set; }
public string Bar { get; set; }
public override string ToString()
{
return string.Format("{0};{1}", Foo, Bar);
}
}
public class CustomSettingConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if( sourceType == typeof(string) )
return true;
else
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string stringValue = value as string;
if( stringValue != null )
{
// Obviously, using more robust parsing in production code is recommended.
string[] parts = stringValue.Split(';');
if( parts.Length == 2 )
return new CustomSetting() { Foo = parts[0], Bar = parts[1] };
else
throw new FormatException("Invalid format");
}
else
return base.ConvertFrom(context, culture, value);
}
}
一些背景资料
TypeConverter 是 .Net 框架中许多字符串转换魔法的幕后推手。它不仅对设置很有用,它还用于 Windows 窗体和组件设计器如何将值从属性网格转换为它们的目标类型,以及 XAML 如何转换属性值。许多框架的类型都有自定义的 TypeConverter 类,包括所有原始类型,还有像
System.Drawing.Size
或 System.Windows.Thickness
这样的类型以及许多其他类型。从您自己的代码中使用 TypeConverter 非常简单,您需要做的就是:
TypeConverter converter = TypeDescriptor.GetConverter(typeof(TargetType));
if( converter != null && converter.CanConvertFrom(typeof(SourceType)) )
targetValue = (TargetType)converter.ConvertFrom(sourceValue);
支持的源类型各不相同,但
string
是最常见的一种。与无处不在但不太灵活的 Convert
类(仅支持原始类型)相比,这是一种更强大(但不幸的是鲜为人知)的字符串转换方法。