设置中的自定义类型

本文关键字:类型 自定义 设置 | 更新日期: 2023-09-27 18:00:11

如何在设置中拥有自己的类型。

我成功地将它们放在了设置表中,但问题是我无法设置默认值。问题是我在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.SizeSystem.Windows.Thickness等类型。

从您自己的代码中使用TypeConverter非常容易,您所需要做的就是:

TypeConverter converter = TypeDescriptor.GetConverter(typeof(TargetType));
if( converter != null && converter.CanConvertFrom(typeof(SourceType)) )
    targetValue = (TargetType)converter.ConvertFrom(sourceValue);

支持的源类型各不相同,但string是最常见的一种。与普遍存在但不太灵活的Convert类(仅支持基元类型)相比,它是一种更强大(不幸的是,鲜为人知)的从字符串转换值的方法。