设置中的自定义类型

NDe*_*per 4 .net c#

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

我成功将它们放在设置表中,但问题是我无法设置默认值.问题是我无法在app.config中看到设置.

Sve*_*ven 7

如果我正确解释你的问题,你有一个自定义类型,让我们调用它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);
    }
}
Run Code Online (Sandbox Code Playgroud)

一些背景资料

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);
Run Code Online (Sandbox Code Playgroud)

支持哪些源类型各不相同,但string最常见.它是一种更强大的(并且遗憾的是鲜为人知)从字符串转换值的方法,而不是无处不在但灵活性较低的Convert类(仅支持基本类型).